21

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)?

evuez
  • 3,257
  • 4
  • 29
  • 44

1 Answers1

19

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.

CodeCaster
  • 147,647
  • 23
  • 218
  • 272
  • Would that not violate idempotancy (required for a PUT) if the resource returned a 201 the first PUT request, but a 200 or 204 on subsequent request? – Ray Jun 28 '17 at 07:45
  • 5
    @Ray no, because idempotence is about _the result on the server_, or more specificaly the byte content of the resource identified by the request URL, not about the content of the response message. The result on the server doesn't change on successive PUTs of the same resource. :) See for example: [_"Note that while idempotent operations produce the same result on the server (no side effects), the response itself may not be the same (e.g. a resource's state may change between requests)"_](http://www.restapitutorial.com/lessons/idempotency.html). – CodeCaster Jun 28 '17 at 07:46
  • Ah... thanks for the clarification--makes complete sense. – Ray Jun 28 '17 at 07:54
  • For completion: The answers in this post [HTTP status code for update and delete?](https://stackoverflow.com/questions/2342579/http-status-code-for-update-and-delete) are quite helpful. – thinwybk Feb 16 '18 at 09:27