What would be the correct HTTP status to return when I am performing the POST request to create a new user, but one of its parameters is incorrect - the company id I am including with the user data doesn't exist in the database.
POST data: {username: 'newuser', age: 99, company_id: 34}
the company with id 34 does not exist in the database.
I was thinking whether that could be:
- 400, kind of invalid data, but it is valid but nonexistent id
- 404 - but it is not so clear which resource does not exist
- 409, because it is kind of conflict and the user can resolve that by changing the company id
- 422?
- or 500 - because it is kind of database error while non existing id's are not allowed there
400
or422
First of all, keep in min that it's a client error, so
5xx
status codes are not suitable here. You should pick a4xx
status code then.The most obvious options are
400
and422
:400
.422
to indicate that the request entity cannot be processed by the server.See the following quote from the RFC 4918 (for your situation, just read JSON when it says XML):
A similar situation was addressed in this answer.
For example purposes, the GitHub API v3 also returns
422
if the content of the payload contains invalid values (but is syntactically valid):Michael Kropat put together a set of diagrams that's pretty insightful when it comes to picking the most suitable status code. See the following diagram for
4xx
status codes: