17

Basically, one feature of my app is to retrieve the logged user's friends.

Actually, I hesitate between both kind of endpoints:

  1. GET /api/users/friends
  2. GET /api/users/:userId/friends

Using 1, userId would be reachable through the authentication token.
Using 2, server would have to additionally check for the correspondance between the passed userId, and the logged user id specified in the auth token so that it avoids any malicious access to other user data, like friends.

So 1 should be enough, but it doesn't sound like a standard rest url.

What is a good practice?

Mik378
  • 3,926

2 Answers2

12

The first solution has a benefit of avoiding data duplication. The request plainly means:

Hello, I'm John. Give me the list of my friends.

If possible, I would even shorten it to GET /api/friends.

On the other hand, if you expect to be able to access friends of other users, the second solution appears the good one. The request means:

Hello, I'm John. Give me the list of friends of John.

but can also be:

Hello, I'm John. Give me the list of friends of Mary.

For instance, one situation where such change can be possible is where a person can find her own friends, but also friends of her friends.

3

Rest Api's must be hypertext driven ! As you would click from one link to another in a standard html page.

An URL is a unique identifier to a resource. Having an url representing more than one resource is in total disacordance with ReST.

With your example, the following url :

/api/users/:userId

should have a link in its response to the :userId friends url

Roy Fielding's dissertation contains a set of constraints needed to comply to ReST.

http://roy.gbiv.com/untangled/2008/rest-apis-must-be-hypertext-driven http://fr.slideshare.net/rnewton/2013-06q-connycrestfulwebapis http://www.ics.uci.edu/~fielding/pubs/dissertation/rest_arch_style.htm