Kevin Doyon
Kevin Doyon

Reputation: 3578

RESTful API: What to do when there is nothing to return

From what I understand about RESTful APIs:

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

Answers (2)

Ilio Catallo
Ilio Catallo

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

stevieg
stevieg

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

Related Questions