API Design – When to Use Nested Resources in a RESTful API

apiapi-designrest

I have two resources: users and links.

Users can have several links associated with them. I have designed my RESTful API so that you can reach the links associated with a user at the following URI:

/users/:id/links

However, I always need to have a URI for just links – sometimes I might want all links, regardless of user.

For this I have:

/links

Does this sound okay? Having two URIs for links?

I wonder if I should instead reach the links for a user with a URI such as:

/links/user/:id or /links/?user=:id

This way, I only have one resource for links.

Best Answer

No, there is nothing wrong with having multiple resources for the same "thing", in this case lists of links.

We were recently struggling with the same problem. Our decision was to have all resources where there is not a strict ownership not to be nested. In other words, the links would be modeled under

/links -- all links
/links/:linkid -- a particular link

Then, filters on the links collection are expressed as query parameters. So to get the links of a certain user, you would use:

/links?user=/users/:userid

This also allows for easier composition of filters:

/links?user=/users/10&since=2013-01-01

And it is easy to understand conceptually - you have a collection of items, and you add filters to it.

That being said, there is nothing more "RESTful" about this approach than any other URI naming scheme. It's just a convention we found human-readable and easy for us developers to understand and embrace. REST doesn't care about what you put in your resource identifiers.