Search code examples
restrestful-architecturehttp-response-codes

Proper response code for RESTful API method [POST/PUT] when the entity from parameter doesn't exist (or the access is denied)


I have a RESTful API method that creates/updates an entity (e.g POST /classes or PUT /classes/:id) with a few parameters. One of the parameters (e.g. teacher) is an ID of some other entity of a different kind.

My question is what is a correct response code for this method when the entity indicated by the parameter doesn't exist (or the user has no access to this entity).

My choice is (for both POST and PUT methods):

  • 404 if the entity from parameter doesn't exist,
  • 403 if we have no access to the entity from the parameter (but the information about existence of this entity is not a secret),
  • 404 if we have no access to the entity from the parameter (in case the information about this entity should remain a secret).

I feel that this is very descriptive and clear (along with some error message). However, I'd like to consider potential alternatives or have a confirmation that my approach is not a bad design.


Solution

  • 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.
    -- RFC 7231

    Emphasis mine. 404 is a non-sensical error in the use case you describe, because of course there is no current representation of the target resource - you're trying to create it. 400 would be a better status code, along with a response object explaining that the referenced object doesn't exist.