RESTful APIs and HTTP codes

Few days back I was having an internal discussion with my team on improving the way we develop RESTful APIs. One point that is interesting to mention here and my purpose of writing this post is "Using HTTP response codes".

With my past experience, I have noticed that developer make a mistake of re-inventing the wheel when it comes to sending response from server. They usually send HTTP 200 with an object having error or success details. Here is how it goes:

Success:

Failure:

Unauthenticated:

If we go with above solution we will have 2 important thing to consider.

- Coming up with custom error codes for entire application,

This is not always easy to identify errors generated by servers and by application. For example authentication failure can occur at resource level or by user role.

- Building custom error handler at client side. 

For handling this developers usually use following approach which is a totally bad one in my view because you are handling errors in success whereas you error callback done almost nothing.

Using jQuery ajax:

Alternatively, if we use HTTP built-in error codes we will have following benefits

  • Application will be using standard HTTP codes so no new error code introduced except for highly custom situation. We can define our error codes for these situations send them as response.
  • All error codes will be sent as HTTP headers so no need to parse the response.
  • No need of adding custom error handler in success method as all libraries are built-in with such functionalities.

I hope this post will help you understand how to go with error handling in your RESTful application.

Do let me know of your thought by leave comments.

Further readings:
https://apigee.com/about/blog/technology/restful-api-design-what-about-errors
https://www.quora.com/What-is-the-proper-use-of-HTTP-status-codes-for-errors-in-a-REST-API

Comments