Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

REST API Http status code best practices

We are writing a REST API that's going to be exposed publicly and used by lot of third party developers. I am looking at best practices for http status codes especially in error cases.

Our application has lots of components internally to which the API is the interface. If there are any errors in the internal components, should I return a 500 with appropriate error message ?

When going through SO, I found some blogs / SO threads which suggested different ways but none of them had a concrete answer.

Any help on this is greatly appreciated.

like image 473
M22an Avatar asked Apr 25 '17 05:04

M22an


1 Answers

This is highly subjective. Here's my opinion, having written several moderately complex APIs.

Realize that HTTP status codes won't map neatly to the kinds of errors your internal components will return. They weren't designed to.

The basic rule to follow is 200 is OK, anything else is an error.

I use essentially only these 4 non-OK status codes:

400 = bad request. The caller sent invalid request parameters. 401 = unauthorized. The caller lacks permissions to make the request. 404 = not found. The caller requested a resource that could not be found or does not exist. 500 = internal server error. Everything else. Something bad happened and the caller probably can't do anything about itt.

That's it for HTTP status codes, as far as I'm concerned.

But I don't stop there. I always return a JSON response that contains my own error code, message, and -- in test environments -- stack trace. My error code is a number that callers can program against, as needed. That's the real error code, as far as I'm concerned.

like image 169
Mike Taverne Avatar answered Oct 02 '22 16:10

Mike Taverne