400 Bad Request
400 Bad Request
is the first error code. Every status that starts with a
4
indicates that the client did something wrong. If the status starts with a
5
it means that the server did something wrong.
400 Bad Request
is used as a generic error code. It’s a useful default error
code if there’s no specific error code that’s a better fit.
There’s often a lot of discussion about which 4xx
code is the most appropriate
for any different situations. This might be because there’s many, and it’s not
always super clear what the distinctions between them are.
The most important thing to remember when selecting the appropriate code is: “can a generic client do something with this response?”. If the answer is no, it might not matter as much which error code is returned.
For example, when a client sees a 401
it might know to show a login window.
When a client sees a 403
, it might know to tell the end-user that the reason
their operation failed, was because of permissions-related issues.
Those are good reasons to show an error code, but those reasons don’t always
exists. For those cases it’s fine to just use the generic status code 400
.
Response bodies
When returning any error, you should also return a response body with more information about the failure. If your client is a browser, this might be user-friendly HTML page. If your client is some kind of JSON-based client, it might be good idea to use the standard application/problem+json response code.
Example
HTTP/1.1 400 Bad Request
Content-Type: application/problem+json
{
"type": "https://example.org/impolite",
"title": "Request was not polite enough",
"detail": "HTTP requests must be made using a 'Please' HTTP header.
}
References
- RFC7231, Section 6.5.1 - 400 Bad Request
- RFC7807 - Problem details for HTTP APIs
- How to think about HTTP Status codes - Article by Mark Nottingham.