Let's take the following API:
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?
CodePudding user response:
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.
CodePudding user response:
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.