Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to design URL to return data from the current user in a REST API?

I have a REST based service where a user can return a list of their own books (this is a private list).

The URL is currently ../api/users/{userId}/books

With each call they will also be supplying an authentication token supplied earlier.

My question(s) is:

  1. Is supplying the userId in the URL redundant? As we get a token with each call we can find out which user is performing the call and return their list of books. The userId is not strictly required.

  2. Would removing the userId break REST principles as /users/books/ looks like it should return all books for all users?

  3. Should I just bite the bullet and authenticate them against the token and then check that the token belongs to the same userId?

like image 961
ADringer Avatar asked Jan 12 '16 11:01

ADringer


People also ask

What is the recommended method and URL pattern for retrieving a specific user?

The GET /api/v2/users/{id} endpoint allows you to retrieve a specific user using their Auth0 user ID. This endpoint is immediately consistent, and as such, we recommend that you use this endpoint for: User searches run during the authentication process.

Which REST URI is used to retrieve all the users?

Last Updated October 27, 2022. This REST API is used to retrieve all the users of CA NIM SM.


1 Answers

Short answer

You could use me in the URL to refer to the current user. With this approach, you would have a URL as following: /users/me/books.

An answer for each question

Is supplying the userId in the URL redundant? As we get a token with each call we can find out which user is performing the call and return their list of books. The userId is not strictly required.

You could consider doing something like this: /users/me/books. Where me refers to the current user. It's easier to understand than /users/books, which can be used to return all books from the users.

For some flexibility, besides /users/me/books, you could support /users/{userId}/books.

The URL /users/me can be used to return data from the current user. Many APIs, such as StackExchange, Facebook, Spotify and Google+ adopt this approach.

Would removing the userId break REST principles as /users/books/ looks like it should return all books for all users?

I don't think it will break any REST principles, but I think your resources will not be properly indetified. As I answered above, I would use /users/me/books and also support /users/{userId}/books.

Should I just bite the bullet and authenticate them against the token and then check that the token belongs to the same userId?

When using the userId in the URL to request private information from a user, there's no harm in checking if the token belongs to the user with the userId included in the URL.

like image 171
cassiomolin Avatar answered Sep 22 '22 23:09

cassiomolin