Friday 5 October 2012

REST Web Service API HTTP Response Status Codes

What HTTP status codes should your REST web service API be returning to clients?  Does it matter?  Before we launch into this topic, a quick recap of some interesting HTTP status codes:

200 - "OK"  All is well
204 - "No Content"  Nothing returned, but all is still well
400 - "Bad Request"  There is problem on the client's side
500 - "Internal Server Error" There is a problem on the server side
301 - "Moved Permanently" The resource has moved
303 - "See Other Server" Returns a URI to another resource
404 - "Not Found" Server has no clue what the client is asking for
409 - "Conflict" Client has tried to perform an operation that would leave one or more resources in an inconsistent state
401 - "Unauthorized" Client attempted access to a resource without providing the necessary authentication credentials
403 - "Forbidden" Client is not authorised to access a resource

HTTP response status codes matter to clients because they give a clue as to what the payload of the response will contain.  So 200 tells the client that they have received the resource they asked for, 400 tells them they didn't because something was wrong on the client side. 404 says the requested resource wasn't there. 401 is useful because it means authentication failed.  403 says authentication was fine but the client was not authorised to access the requested resource.  500 says that something has gone wrong, and the client could consider retrying later (if the request was idempotent, i.e. safe for retry)

So what about the other, more exotic codes, like for example 206 Partial Content, say if part of the request could be accommodated?  Or perhaps a 501 Not Implemented to indicate work in progress services?

Personally I think these should be avoided.  There are potentially many server layers between the client and the REST service, things like Akamai Content Delivery Management, which may be already using these codes to their own ends (e.g. redirecting the request to a friendly something-has-gone-wrong page), so there is no guarantee that these layers won't interfere with your response.

Some RESTful API providers go the whole hog and just return 200 codes for this reason, but I think that is unhelpful.

So, in summary, my view is:
  • 200 for valid response, 
  • 400 for client error, e.g. a request validation problem, 
  • 500 for serious errors (but without bothering to return content unless you're sure it won't be interfered with).
  • 401 and 403 should be reserved for URI access, not fine-grained authorisation control.
  • 404 should be used if the resource is not found, e.g. if the URL is wrong, not for more subtle business errors .
Share: