'Nested REST API resource not found

This feels like what should be a very common question but I cannot find anything related to it. I am working on a 'REST' API with nested / sub-resources

GET /user/1
GET /user/1/friends

I believe by now it is fairly widely accepted that if user 1 does not exist, a 404 response is expected from the first URL (with a body response detailing the Resource is not found).

However for the second URL, if user 1 does exist, but has no friends, what should be returned?

  • 404 (feels weird)
  • 200 with a body of an empty result
  • Something else

Note; I am not saying this is the best REST implementation; this API has been inherited. Personally I would do something like

GET /friends?user=1

which would return a 200 empty array, but I cannot change the nested resource API path URLs, just the responses.

Also I realize REST depends more on the response body content (hyperlink media), so this is more about clean API design, but I still think the HTTP response codes fall into REST.



Solution 1:[1]

In the request for GET /user/1/friends,

User 1 does not exist: 404, the user does not exist, so sub-resource/collection also does not exist.

User 1 does exist: 200, The sub-resource/collection being queried does exist, it is empty.

Query on /users/1/nonExistentCollection: 404, the collection does not exist.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Cole Murray