Reputation: 23214
In my API I have the following resource:
example.com/api/v1/users/me/sites
example.com/api/v1/users/123/sites
Which returns all sites for the current or given user.
Now, what if I want to fetch all sites, and ignore users. I'd assume that would have the following URL:
example.com/api/v1/sites
Which then strikes me as somewhat odd to have sites as a root resource and as a subresource for users.
Is this an OK approach or is it common to do this some other way?
Or should it be something like:
example.com/api/v1/users/sites
Where there is no Id for the users?
Upvotes: 4
Views: 2316
Reputation: 67296
For me, as a rule of thumb, I look at what I'm returning from the API and this usually informs what I'm representing.
For example, you are actually returning sites, not users for the URL: example.com/api/v1/users/123/sites. In this case, I would prefer to address sites, as that is what is being returned.
So, I would opt for this URL: example.com/api/v1/sites?user=123
IMHO, this is utilizing the query string as an actual query for sites.
So, for the site representation I would build it up like this:
All sites: example.com/api/v1/sites
A particular site: example.com/api/v1/sites/1
A user's site: example.com/api/v1/sites?user=123
Current user's site: example.com/api/v1/sites?user=current
Upvotes: 3
Reputation: 44316
I wanted to add something to this interesting question.
You could for example find out which user "owns" a certain site by doing
example.com/api/v1/sites/[site_id]/user
This would return the user resource that owns site with site_id.
Another example could be users and addresses. If you allow users to share an address resource (addresses can have several users) you could do this:
example.com/api/v1/users/[user_id]/address
=> returns address for user with user_id. Doing a DELETE
operation on that path will not delete the whole address resource but merely the connection between the user and the address. To delete the address itself you should do DELETE
on example.com/api/v1/addresses/[address_id]
example.com/api/v1/addresses/[address_id]/users
=> returns users that live at that address and similarly as deleting the address from a user you can also delete a user from an address with DELETE
on example.com/api/v1/addresses/[address_id]/users/[user_id]
The relationship between Address and User (what @Aliostad refers to as association as composition) itself is a resource and can be accessed and also deleted without deleting the resources themselves.
Upvotes: 2
Reputation: 81660
There is no problem with having
example.com/api/v1/sites
In addtion to
example.com/api/v1/users
especially each seems to be a root aggregate.
So if association is composition rather than aggregation (between site and user) then it is not only OK, but also correct to have them as the root URL fragment.
Upvotes: 2