Given the requirement other departments have for our REST API they would like to use POST
not just for CREATE but for UPDATE OR CREATE. I know in a RESTful API PUT
could or should be used for that, but because clients have to update information that is used to build the URI, we cannot use that. It would change the URI and make PUT
not idempotent anymore... (the old URI would not exist after the first PUT
).
tl;dr we cannot use PUT
In the HTTP/1.1 specs POST is defined as
The POST method is used to request that the origin server accept the entity enclosed in the request as a new subordinate of the resource identified by the Request-URI
but also
The action performed by the POST method might not result in a resource that can be identified by a URI.
To stay RESTful I would explain the update functionality as an Deletion of the old element and then a Creation of the new one, which would be an acceptable functionality for POST
I would say.
We would return a #201
when creation was successful and a #200
when it was just an update.
In our API it is "possible" to address the right element without the URI (e.g. for updating it with POST
), because all the URI building primary key parts are in the resource body, so the API knows which element the client wants to access.
Example
(This is just an example of the behavior for POST
. Not for the data structure of the resource. Of course using PUT
would be completely right for /cars/
)
POST /cars/ HTTP/1.1
<car>
<id>7</id>
<status>broken</status>
</car>
response: #201
and then
POST /cars/ HTTP/1.1
<car>
<id>7</id>
<status>fine</status>
</car>
response: #200
now a GET
on /cars/7
would return the following:
<car>
<id>7</id>
<status>fine</status>
</car>