Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

REST API, path variable vs request param

Tags:

rest

I am currently writing a webservice providing access to some resources. I try to follow REST but I am facing a problem concerning some parts of my API.

I have the follwing uris:

  • /myservice/users/ : to get all users
  • /myservice/users/{userId} : to get a specific user
  • /myservice/badges/ : to get all badges
  • /myservice/badges/{badgeId} : to get a specific badge

Now, my problem is, i have to implement a way to get all users that have a particular badge. I can consider that this is just a filter I apply on the list of users, hence the following uri:

  • /myservice/users/?filter=badge:{badgeId}

Or I can consider that this is just a sub-resources of a badge, hence the following uri:

  • /myservice/badges/{badgeId}/users/

Which one seems the must 'REST-compliant' ?

I must say I have read some posts on this subject specifically this one: Rest Standard: Path parameters or Request parameters but they don't seem to cover my problem.

like image 325
Guillaume D Avatar asked Mar 27 '12 16:03

Guillaume D


1 Answers

If you're looking to be RESTful, consider using HATEOAS (horrible acronym, but key to being truly RESTful).

Using HATEOAS, your Badge representation could look something like this:

<badge>
  <id>1234</id>
  <name>Admin</name>
  <link rel = "/rel/users"
        href = "/myservice/users?badge=1234" />
  <link rel = "self"
        href = "/myservice/badges/1234" />
</badge>

This allows your clients to be decoupled from your server's URI scheme as they simply GET on whatever href the /rel/users link provides. Granted your server still needs to define a URI scheme internally, but if at some point down the road you decide you don't care for it, you can easily change it without breaking your clients. For instance, you may want to change your URI scheme to your second option, which would cause your Badge representation to change to this:

<badge>
  <id>1234</id>
  <name>Admin</name>
  <link rel = "/rel/users"
        href = "/myservice/badges/1234/users" />
  <link rel = "self"
        href = "/myservice/badges/1234" />
</badge>

Clients using the /rel/users link relation aren't affected by the URI change. What this boils down to is ... use HATEOS, and the URI scheme doesn't really matter all that much.

Cheers!

like image 178
Andaris Avatar answered Sep 19 '22 13:09

Andaris