Reputation: 19050
I'm developing an API and I always try to use the most correct http status codes for each scenario.
One of this scenarios is the response for POST requests. Per example, a POST method for an endpoint /orders/
receive some informations, like a customer
:
{
customerDocument: {number: "123.456.789"},
// other informations for create a order
}
So, my questions is: if this number
from customerDocument
not exists, is it Ok to return a 404 status code error with a nice message telling that the customer was not found?
I normally use 404 only for GET in the specific resources (the most obvious usage), like:
/customers/{number}/
In business validations like "The customer is not active", I normally use the http status code 422 for any http method (POST, PUT, GET, etc). I'm in doubt if I can use 404 or 422 for my POST example.
Upvotes: 10
Views: 8097
Reputation: 16226
I think 400
is the appropriate status code in this scenario, given its definition from Wikipedia:
400 Bad Request
The server cannot or will not process the request due to an apparent client error.
According to the description, semantically, 422
is better ("The request was well-formed but was unable to be followed due to semantic errors."). However, 422
is introduced for WebDAV, so it is better to use general purpose status code such as 400
.
400
is not the perfect status code, as whether document number exists or valid is not so apparent. However, excludes special-purpose status code such as 422
, 400
is the best option.
Why 404
is not appropriate?
From RESTful API point of view, endpoint /orders/
is a resource, no matter it accepts GET
or POST
or something else. 404
is only appropriate when the resource /orders/
itself does not exist. If /orders/
endpoint exist, but its invocation failed (no matter what reasons), the response status code must be something other than 404
.
Upvotes: 18