Search code examples
resthttphttp-status-code-404http-status-codes

appropriate HTTP status code for non-existent resources in REST API?


I am engineering a REST API server application, trying to establish a rule for the server response when a resource does not exist. While we can define our internal codes within our team, there is a controversy regarding the HTTP status code.

Consider an endpoint POST /a (body: { "bid": 123 }). This endpoint is for creating a user-owned 'a' resource. During creation, a 'b' resource is needed, so the id of 'b' is included in the body as a payload. However, if there is no resource with id=123 in 'b', should this be treated as 404 Not Found?

I would appreciate your insights from both the principles of REST and conventions. It would be even better if you could provide references to official documents like RFC.

currently I chose 404 not found. But my team says it is wrong. What is correct?


Solution

  • However, if there is no resource with id=123 in 'b', should this be treated as 404 Not Found?

    Probably not.

    Key idea: HTTP status codes are metadata of the transfer-documents-over-a-network domain, they are there to describe the nature of the response to general purpose components (browsers, proxies, and so on) so that those components can do interesting things.


    In the case you describe, there is certainly a problem in the request, so some 4xx client error is appropriate.

    404, however, indicates that the target resource does not have a current representation. The target resource is the resource identified by the request-target in the request-line.

    Put simply, to send a 404 response is to imply that the HTTP request had a spelling error in the URI of the requested resource.

    In your example:

    POST /a HTTP/1.1
    

    the target resource is that resource identified by /a. And that part of the message is correct: the spelling of the request-target does match the identifier of your request processor; therefore a 404 response is misleading.

    What you want is one of the registered status codes that implicate the request body, rather than the request target.

    422 Unprocessable Content is a better fit.