Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rest API design multiple URLs to same resource?

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?

like image 395
Roger Johansson Avatar asked Mar 22 '23 13:03

Roger Johansson


2 Answers

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:

  1. All sites: example.com/api/v1/sites

  2. A particular site: example.com/api/v1/sites/1

  3. A user's site: example.com/api/v1/sites?user=123

  4. Current user's site: example.com/api/v1/sites?user=current

like image 175
Davin Tryon Avatar answered Mar 28 '23 14:03

Davin Tryon


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.

like image 39
Aliostad Avatar answered Mar 28 '23 12:03

Aliostad