Working with budding API developers I often notice that many of them confuse with HTTP status codes and their usage. Let me try to explain the usage of the 4XX and 5XX series at a high level.
When do you send a 400 Bad Request to the API caller? Answer is straight forward, when something is wrong with the request. Let’s take an example,
Your API is something like
and the caller invokes
We send the caller a bad request.
Let’s say now the user send
But you don’t have a user by the id 123.
You will never send a 400 or 500 series.
Now let’s say, for that invocation, your code throws an error internally, as you never thought someone will call your API with a non existent id, now you need to tell the user that you screwed up and you are gonna fix it. Send an internal server error, 500.
I generally see this misconception among many developers that you send a 400 or 500 series error code only in case of an error or exception. Not necessary, you can validate a user input and send the user a 400 bad request, and not wait till your code throws an exception on input. In fact, I would suggest developers to validate input parameters and send a bad request immediately, by validation I mean non business validations like empty or null checks, format validations etc.
if userId == null send bad request 400
Similarly, some internal service that is needed to service this request is down. Don’t wait for things to break.
Then you always have status codes 403 for security, 405 for method errors and many more to provide granularity. Like don’t tell the caller there is a bad request unless you know its a genuine user, else send 403 and forget it.
Same is the case for server errors.
The key point to understand is that, these codes are to help genuine users to fix their request or tell them we need to fix something without telling them nitty-gritties to avoid vulnerabilities.
So ask yourself,
- who needs to fix this
- what should I tell my user about this
- By sending a particular status code will I be exposed to vulnerabilities
and the right code will come to you.
Here is a very good further reading I would suggest to API developers.