0

Let's take the following API:

enter image description here

One of the things that I'm always a bit unclear about is when updating the /posts/{id} item. If a post consists of:

  • ID
  • Title
  • Author
  • PostedAt
  • Body

What if we want to wipe out a previous post and update it with the new post (that is, something like getByID.update(title, author, body) -- would this be done via a PUT request or a POST request? Would it ever make sense to POST to a /posts/{id} or does a POST essentially mean it creates a new entry, whereas a PUT only updates an existing entry via its PK -- i.e., a POST is like a INSERT in SQL and a PUT is like an UPDATE in SQL.

Additionally, what if there is something like a List field? For example, /posts/{id}/tags, where tags could be something like programming, c++, rest. What if someone performed a delete operation here -- would it be deleting all the tags, or just a single tag?

Helen
  • 87,344
  • 17
  • 243
  • 314
David542
  • 104,438
  • 178
  • 489
  • 842
  • 1
    Do these links answer your question? [What is the difference between POST and PUT in HTTP?](https://stackoverflow.com/q/630453/113116), [What's the difference between a POST and a PUT HTTP REQUEST?](https://stackoverflow.com/q/107390/113116), [What is the difference between PUT, POST and PATCH?](https://stackoverflow.com/q/31089221/113116), [Use POST instead of PUT](https://stackoverflow.com/q/43258725/113116) – Helen Jul 25 '22 at 06:25

2 Answers2

1

POST: creation of a new thing, where the location (ID) of the new thing will be determined by the server. The response is expected to contain a Location header telling the client where the object ended up (POST-redirect-GET pattern).

PUT: creation of a new thing at a client-defined location (in cases where that's allowable), or replacement of the thing at a given location (this includes "updates" where the body being sent by the client is a complete representation of the object, just as you would get from a GET).

PATCH: in-place partial-update of the thing at a given location.

hobbs
  • 223,387
  • 19
  • 210
  • 288
  • thanks, could you please elaborate, maybe with an example or so (from another docs site?) of an example POST with the redirect-GET pattern, and then a PATCH? – David542 Jul 25 '22 at 20:47
0

POST is for creation only. Use partial update with PATCH instead, or PUT if the other fields are read-only.

Well in theory you can create a REST API with GET and POST only, but if there are better methods available, then you should use those.

inf3rno
  • 24,976
  • 11
  • 115
  • 197