Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTTP status code for PUT

Tags:

rest

http

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

like image 446
evuez Avatar asked Dec 04 '15 11:12

evuez


People also ask

Should Put return 200 or 204?

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.

What is HTTP PUT?

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.

What is the response code for PUT method?

Responses to the PUT method are non-cacheable. PUT requests usually respond back with status code 200.

What is a 202 status code?

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.


1 Answers

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.

like image 95
CodeCaster Avatar answered Sep 24 '22 03:09

CodeCaster