Search code examples
resthttphttp-status-codes

In an entity creation request(POST) sent to Rest API, what is the best status code to return if no foreign key is found?


I have a rest api that meets the request for a post like the one below.

POST /api/v1/products HTTP/1.1
Content-Type: application/json

{
    "name": "product test",
    "categoryId": 111,
    "unitsInStock": 12,
    "unitPrice": 11
}

If categoryId is not found here I want to return error. What is the best http status code for this? I don't think it's a 404 because I haven't requested a resource.


Solution

  • Status codes are meta data in the transfer of documents over a network domain.

    This is a problem that you can trace directly to the request (specifically, that the information in the request body isn't to your liking) so a 4xx Client Error is appropriate.

    The information describing the details of the client belong in the body of the response. The status code is there to give general purpose components a coarse understanding of the semantics of the response body.

    The IANA status code registry enumerates a number of possibilities; remember that the description/reason-phrase is not the definition -- the definition will be in the reference document listed in the registration.

    I would consider the following candidates

    403, on its own, is perfectly satisfactory "I understood your request, but I'm not going to fulfill it." That's a really broad message, though, and in particular your operators might not be happy trying to distinguish these events in your access logs.

    409 is probably fine. "current state of the target resource" is a bit fuzzy. As far as I can tell, general purpose components will treat 409 identically to 403, so even if the meaning isn't perfect, you are likely to get away with it?