I don't think 404
is suitable for this situation if the request has been performed to a URL that points to a resource that does exist. The problem is in the payload, so 404
has nothing to do with it.
The syntax of the JSON document is valid, so 400
is not suitable either.
What you have is an unprocessable entity due to invalid data, so 422
would be the best alternative here. Keep reading for a more detailed explanation.
Not found and Bad request
Assuming that the request has been performed to a URL that locates a valid resource (that is, a resource that exists), returning 404
is not suitable for this situation and it may yield misunderstanding:
6.5.4. 404 Not Found
The 404
(Not Found) status code indicates that the origin server did
not find a current representation for the target resource or is not
willing to disclose that one exists. A 404
status code does not
indicate whether this lack of representation is temporary or
permanent; the 410
(Gone) status code is preferred over 404
if the
origin server knows, presumably through some configurable means, that
the condition is likely to be permanent.
Returning 400
with a descriptive message in the payload would be suitable for this situation if the JSON was malformed, but that's not the case:
6.5.1. 400 Bad Request
The 400
(Bad Request) status code indicates that the server cannot or
will not process the request due to something that is perceived to be
a client error (e.g., malformed request syntax, invalid request
message framing, or deceptive request routing).
Unprocessable entity
As a matter of fact, what you have is an entity that cannot be processed by the server due to invalid data. So returning 422
and details about the error in the response payload would be the most suitable approach for this situation:
11.2. 422 Unprocessable Entity
The 422
(Unprocessable Entity) status code means the server
understands the content type of the request entity (hence a
415
(Unsupported Media Type) status code is inappropriate), and the
syntax of the request entity is correct (thus a 400
(Bad Request)
status code is inappropriate) but was unable to process the contained
instructions. For example, this error condition may occur if an XML
request body contains well-formed (i.e., syntactically correct), but
semantically erroneous, XML instructions.
Just read JSON when it says XML.
You also may find this answer helpful.
Problem details for HTTP APIs
HTTP status codes are sometimes not sufficient to convey enough information about an error to be helpful. The RFC 7807 defines simple JSON and XML document formats to inform the client about a problem in a HTTP API.
It also defines the application/problem+json
and application/problem+xml
media types.
Picking the right 4xx status code
The following diagram (extracted from this page) is pretty insightful when it comes to picking the most suitable 4xx
status code. Hopefully it will help you:
