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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With