Search code examples
restrestful-urlrestful-architecture

RESTful API subresource pattern


In designing a RESTful API, the following call gives us basic information on user 123 (first name, last name, etc):

/api/users/123

We have a lot of information on users so we make additional calls to get subresources on a user like their cart:

/api/users/123/cart

For an admin page we would like to see all the cart information for all the users. A big table listing each user and some details about their cart. Obviously we don't want to make a separate API call for each user (tons of requests). How would this be done using RESTful API patterns?

/api/carts/users came to mind but then you'd in theory have 2 ways to get a specific user's cart by going /api/carts/users/123.


Solution

  • For some reason I was under the assumption that having 2 URIs to the same resource was a bad thing. In my situation /api/users/123/cart and /api/carts/users/123 would return the same data. Through more research I've learned from countless sources that it's acceptable to have multiple URIs to the same resource if it makes sense to the end user.

    In my case I probably wont expose /api/carts/users/123, but I'm planning on using /api/carts/users with some query parameters to return a subset of carts in the system. Similarly, I'm going to have /api/carts/orgs to search org carts.

    A really good site I found with examples and clear explanations was the REST API Tutorial. I hope this helps others with planning their API URIs.