Reputation: 3578
From what I understand about RESTful APIs:
If I'm asking for an ID that doesn't exist (for example /users/999/posts
where user 999 doesn't exist), it should return a 404
status code.
If I'm asking for a list of object, using valid IDs, but there is nothing to return, it should return 200
status code with empty array (for example /users/999/posts
where user 999 exists but never posted anything)
Questions I've seen here are usually about those two cases.
Now my question is about when I have no data, I'm using valid IDs, but I'm supposed to return an object instead of a list.
For example, let's assume that for some reason I don't want to always return the user's address when I ask for /users/999
. I have this different route: /users/999/address
which returns an address object.
What should be returned if that user doesn't have any address? An empty object {}
? 404
status code? 204
status code?
I would think an empty object to be consistent?
Googling, I found this saying:
The call to return the leagues or teams for a given summoner ID will now return a 404 instead of an empty object. This behavior is the correct RESTful behavior when the requested resource (i.e., leagues or teams) doesn’t exist.
So I'm a bit confused as to what the proper RESTful behaviour should be.
Thanks!
Upvotes: 3
Views: 1880
Reputation: 3180
I think a 404
should result from requesting a non-existing address. Indeed, if the address resource does not exist, and the client asks for it (because of an erroneous knowledge on the resource state), the client is making a mistake.
Regarding your point about discovering that a given user has an associated address or not, I would explicit the relationship by using a hypermedia control form the client resource to the address resource, as dictated by the HATEOAS constraint.
Moreover, the address resource is a weak entity w.r.t. the correspoding user. Hence, it is makes sense to return 404
for the two cases. You can still take advantage of the HTTP entity body to better explain what happened.
Upvotes: 1
Reputation: 662
Think about it from the consumer's point of view, would they rather use the same code when there are no addresses, or have to write a special case for no addresses?
I return an empty collection because it's less work for consumers (and for the REST service, but that's a bonus).
If the request was /users/999/addresses
and user 999
didn't exist I'd return a 404
.
EDIT: If /users/999/address is the canonical address for the resource (that is it's incorrect to say /users/999/address/1) then I'd return a 404 because the user requested a specific and precise thing.
Upvotes: 1