Saturday, February 27, 2016

REST API : Using the Correct Return Types

What should DELETE return ?
Depending on the case can return following.

  • 200 OK, if the resource is deleted successfully and there is something to tell the client.
  • 202 Accepted, if the request is accepted but not deleted yet. This response should include some indications. Kind of batch delay , or if deletion takes time or resource marked for deletion and actual deletion happens later...
  • 204 No Content,  if the resource is deleted successfully and there is nothing to tell the client.
  • In subsequent following ‘delete’ request return  404 , if resource doesn’t exists and it’s already deleted …. Idempotence is not about always returning the same result each time (I'm looking at you Twitter).  it just means that issuing the same request multiple times won't produce additional side effects  
What should PUT return ?

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)

What can POST return
  • 201 : for immediate successful creation. Body has the unique if of created entity.
  • 202 : if request to create is taken successfully, but creation is not complete yet.
  • 500 : server side error in creation.

 Following Flow Diagram can be useful

No comments: