REST api: please don't return 200 OK for errors

Please when building REST api do not return 200 OK if there is actually an error.
Too many REST apis return 200 OK but with a field such as success or status that is used to indicate if there was actually an error or not!
e.g. a json example
if error: {"success": "false", "error": "sorry that key already exists"}
and if all is ok: {"success": "true", [{...}, {...} ]}
In both cases 200 OK is returned from server.

There's no need to do that. As a client side developer I need to then have code within my Rest api call success handler that checks the "success" field to determine if the request really succeeded or not. Libraries such as jQuery v1.5 now allow me to specify handlers based on HTTP response codes so it's much cleaner if I get a useful HTTPS response back.

As much as possible, please just use the HTTP response codes instead. If all went ok then just return 200 OK with any response data as appropriate
e.g. from example above if successful: [{...}, {...} ]
Note "success": true is gone, just data returned

But if an error happened then return the appropriate HTTP response code, not 200 OK. There's lots of useful codes to cover typical scenarios such as:
400 Bad Request - e.g. return if data passed to server fails server side validation checks
404 Not Found - e.g. return if a request (e.g. get, update) found no match
409 Conflict - e.g. return if I want to add new data for which a key already exists
500 Server Error - server error

You can still return data with these error codes, but please don't return 200 OK if things are really not ok.


For some inspiration, checkout Amazon SimpleDBs list of return codes.


Returning HTTP response codes in php
In php its easy to return such codes, use the header() method
e.g.

  header($_SERVER["SERVER_PROTOCOL"] . ' 400 Bad Request'); 
  exit(); 

Comments

Popular posts from this blog

deep dive into Material UI TextField built by mui

angular js protractor e2e cheatsheet

react-router v6.4+ loaders, actions, forms and more