Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Picking HTTP status codes for errors from REST-ful services

Tags:

rest

When a client invokes my REST-ful service, it needs to know if the response came back was 'from me' or rather a diagnosis from the containing web server that something awful happened.

One theory is that, if my code is called, it should always return an HTTP OK(=200), and any errors I've got to return should be just represented in the data I return. After all, it's my code that gets the response, not the naked browser.

Somewhat self-evidently, if I'm using REST to generate HTML read directly by a browser, I absolutely must return an error code if there's an error. In the case I care about, it's always Javascript or Java that is interpreting the entrails of the response.

Another possibility is that there is some family of HTTP status codes that I could return with a high confidence that it/they would never be generated by a problem in the surrounding container. Is this the case?

like image 507
bmargulies Avatar asked May 11 '11 19:05

bmargulies


2 Answers

I use the following:

GET

  • 200 OK
  • 400 Bad Request (when input criteria not correct)

POST

  • 202 Accepted (returned by authorization method)
  • 401 Unauthorized (also returned by authorization)

  • 201 Created (when creating a new resource; I also set the location header)

  • 400 Bad Request (when data for creating new entity is invalid or transaction rollback)

PUT

Same as POST

  • 201 Ok
  • 400 Bad Request

DELETE

  • 200 OK
  • 404 Not Found (same as GET)
like image 143
Jason Watts Avatar answered Oct 14 '22 19:10

Jason Watts


I would not know how to avoid that some container returns codes like 404.

4xx codes are meant to handle client errors along with possibly some entity that describes the problem in detail (and thus would mean a combination of both of your mentioned approaches). Since REST relies on HTTP and the according semantics of status as well as methods, always returning 200 in any possible case is a violation of this principle in my opinion.

If you for instance have a request such as http://foo.com/bar/123 which represents a bar ressource with id=123 and you return 200 with some content, the client has no chance to figure out if this was the intended response or some sort of error that occured. Therefore one should try to map error conditions to status codes as discussed in REST: Mapping application errors to HTTP Status codes for example.

like image 43
Dirk Avatar answered Oct 14 '22 19:10

Dirk