A PUT
requests can have many outcomes, and I was wondering which status code would be best for each of them.
Say I want to create a new resources, so I do something like that:
PUT http://example.com/resources/resource-1
And I would get a HTTP 201
because a new resource has been created.
Now I want to update this resource, so I do the same request, with new contents:
PUT http://example.com/resources/resource-1
And I get HTTP 200
or HTTP 204
, because the resource has been updated. But what if I send this request once again with the same contents? Should the server return HTTP 200
or HTTP 204
even if nothing has been updated?
I am aware that HTTP 200
and HTTP 204
both just mean that the request was successfully processed, and even if the data don't change the request can (and should) still be successfully processed. But is there a way to tell the client that the request has been successfully processed but nothing has changed on the server side? And if there is, should it be used for a PUT
request? PUT
being idempotent, should different status be returned depending on the actual processing on the server side (as long as no error occurs during this processing)?
200 OK - This is the most appropriate code for most use-cases. 204 No Content - A proper code for updates that don't return data to the client, for example when just saving a currently edited document. 202 Accepted - If the update is done asynchronous, this code can be used.
HTTP PUT sends data to a resource. The HTTP PUT request allows you to edit existing HTTP resources. The HTTP PUT method requests that the enclosed entity be stored under the supplied Request-URI. If the Request-URI refers to an already existing resource, it is modified.
Responses to the PUT method are non-cacheable. PUT requests usually respond back with status code 200.
The HyperText Transfer Protocol (HTTP) 202 Accepted response status code indicates that the request has been accepted for processing, but the processing has not been completed; in fact, processing may not have started yet.
But is there a way to tell the client that the request has been successfully processed but nothing has changed on the server side?
Yes, but that's not what status codes are for.
Either return 200 OK and a representation of the entity, or 204 No Content and return nothing.
For no change being applied, use a header like ETag. The client can compare the ETag with their previous value, and determine nothing was changed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With