akop
akop

Reputation: 7855

RestApi: 404, 422 or 500?

Lets assume we have two objects. post and comment. post has n-comments.

If I want to get (or change) a comment of a post then I can also do an
[DELETE, GET, PATCH] posts/{postId}/comments/{commentId}
instead of
[DELETE, GET, PATCH] GET comments/{commentId}

But ... what is when the server notice, that the given commentId exits, but has a other postId as the client-request says? Is that a ...

  1. 404 (not found) - because the complete path not exsits.
  2. 422 (unprocessable entity) - because syntax is right, but the semantics are not.
  3. 500 (internal server error) - because its a unexpected condition see (https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/500).

Upvotes: 2

Views: 3654

Answers (1)

cassiomolin
cassiomolin

Reputation: 130927

It's definitely a client error, so the proper status code should be in the 4xx range.


When a resource representation cannot be found for a given URI, then the server is expected to return a response with the 404 status code:

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. [...]


The 422 status code is meant to indicate a payload that is syntactically valid but is semantically invalid.

Consider, for example, you have an endpoint to create comments and the payload should contain the identifier of the post which this comment belongs to:

POST /comments HTTP/1.1
Host: example.org
Content-Type: application/json

{
  "content": "Awesome post!",
  "postId": 1
}

In this situation, if postId refers to a post that doesn't exist, the server should return 422.

Upvotes: 5

Related Questions