Reputation: 63
I'm building a REST API and have a dilemma around the returning response code to a GET operation. I've found many examples and answers online but not for my particular scenario. Here is what I have found and understand so far:
if returning an empty list (say /library/authors/{authorId}/books) an empty list with a response code 200 will suffice
if requesting a specific resource with an id ( say /library/authors/{authorId}/books/{bookId} ) the response will be empty with a 404
That summarizes most of my use cases and I am fine with it.
However, what happens if I access a sub-resource without an id?
For example, for arguments sake, let's say the author can have many books, but only one auto-biography. He either has one or he doesn't. I don't expect the user to pass in the auto-biography id because the system can figure out on its own if one exists, the endpoint is something like this:
GET /library/authors/{authorId}/auto-biography
If the author exists but he has no autobiography (it is NULL), would the http response code be:
Thank you in advance!
Upvotes: 1
Views: 878
Reputation: 57214
Working through the semantics
GET /library/authors/1/auto-biography
/library/authors/1/auto-biography
is an identifier. The resource itself is some concept like "the auto biography of author 1"; notice that we can talk about the resource even though it may not actually exist yet.
A resource can map to the empty set, which allows references to be made to a concept before any realization of that concept exists
The thing that appears in the body of the HTTP response isn't the resource, but a representation of the resource.
So now look at the status codes
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 204 (No Content) status code indicates that the server has successfully fulfilled the request and that there is no additional content to send in the response payload body.
A loose analogy: suppose you try to get the contents of a file. 404
is semantically aligned with FileNotFound; 204
indicates the file is zero bytes long.
404
would normally be accompanied by "a representation containing an explanation of the error situation, and whether it is a temporary or permanent condition." It indicates that the client tried to use a link that shouldn't have been available.
204
, on the other hand, doesn't have anything -- the representation is zero bytes long, how could there be data. It's a special case of a 200
response, advising the client (and intermediary components) that the response body is intentionally left blank.
Upvotes: 2