REST URL Structure – Specifying UserId Best Practices

authenticationhttpresturl

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?

Best Answer

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.

Related Topic