Vitor Santos
Vitor Santos

Reputation: 611

Which HTTP code to use, in a REST API, for a subresource if the parent resource doesn't exist?

My team and I are coding a REST API, but some concepts are still not fully understood.

In a given resource: objective/{id}/goal where goal is collection

If the consumer tries to reach an objective that doesn't exist, the API will return status code 404, pretty simple.

ex: objective/999 returns 404

For some reason the consumer tries to fetch the goals from this non existing resource:

ex: objective/999/goal returns ?

Which is the most suitable code to return? I have a feeling that this should be a 404 too. Some people are considering another error code, because the API should somehow inform that the parent resource doesn't exist in the first place.

Upvotes: 4

Views: 1107

Answers (1)

Timothy Shields
Timothy Shields

Reputation: 79441

Use 404. Keep in mind that a 404 response may contain a response body. So you could respond with something like the following:

Request
GET /objective/7/goal

Response
404 Not Found
{
    "type": "ParentNotFound",
    "description": "The parent resource was not found.",
    "parent_uri": "/objective/7"
}

In general, it's a good idea to include some kind of response body for error status codes. Even when the error status code is being used in a standard way, it's still nice as the API client to see a human message about why I'm seeing the error. The benefit is even greater when the error status code is being used in an almost standard yet slightly off way.

Upvotes: 7

Related Questions