Does a RESTful 'PUT' operation return something?
I was wondering whether a RESTful PUT
operation that returns nothing (null) in the response body complies with relevant specifications for REST transactions.
The HTTP specification (RFC 2616) has a number of recommendations that are applicable. Here is my interpretation:
- HTTP status code
200 OK
for a successful PUT of an update to an existing resource. No response body needed. (Per Section 9.6,204 No Content
is even more appropriate.) - HTTP status code
201 Created
for a successful PUT of a new resource, with the most specific URI for the new resource returned in the Location header field and any other relevant URIs and metadata of the resource echoed in the response body. (RFC 2616 Section 10.2.2) - HTTP status code
409 Conflict
for a PUT that is unsuccessful due to a 3rd-party modification, with a list of differences between the attempted update and the current resource in the response body. (RFC 2616 Section 10.4.10) - HTTP status code
400 Bad Request
for an unsuccessful PUT, with natural-language text (such as English) in the response body that explains why the PUT failed. (RFC 2616 Section 10.4)
As opposed to most of the answers here, I actually think that PUT should return the updated resource (in addition to the HTTP code of course).
The reason why you would want to return the resource as a response for PUT operation is because when you send a resource representation to the server, the server can also apply some processing to this resource, so the client would like to know how does this resource look like after the request completed successfully. (otherwise it will have to issue another GET request).
I think it is possible for the server to return content in response to a PUT. If you are using a response envelop format that allows for sideloaded data (such as the format consumed by ember-data), then you can also include other objects that may have been modified via database triggers, etc. (Sideloaded data is explicitly to reduce # of requests, and this seems like a fine place to optimize.)
If I just accept the PUT and have nothing to report back, I use status code 204 with no body. If I have something to report, I use status code 200, and include a body.
The HTTP/1.1 spec (section 9.6) discusses the appropriate response/error codes. However it doesn't address the response content.
What would you expect ? A simple HTTP response code (200 etc.) seems straightforward and unambiguous to me.
If the backend of the REST API is a SQL relational database, then
- you should have RowVersion in every record that can be updated (to avoid the lost update problem)
- you should always return a new copy of the record after PUT (to get the new RowVersion).
If you don't care about lost updates, or if you want to force your clients to do a GET immediately after a PUT, then don't return anything from PUT.