Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

REST URI Design for resources that belong to a specific user

Tags:

rest

Assume I want to create a very simple todolist RESTful API, where each user owns a list of todos. The user is already authenticated over http BASIC or DIGEST.

At this point I am not sure what the URL scheme should look like. Would it be:

http://servername/todos/

where my server filters the appropriate todos according to the authentification given to me by the http header.

Or should I include the username in the URI instead:

http://servername/users/username/todos/

On some websites I have even seen that they hand over the user name as a parameter like this:

http://servername/todos?username=babsi

As far as I can tell all three choices are stateless as I always receive the username, but just over different sources. From what I can tell to make sure that the URI is accessed by the proper user I always need to check the http header anyways. So which of the ways would you consider the best URI design in REST or should I do in a different way entirely?

like image 574
gebirgsbärbel Avatar asked Oct 04 '22 00:10

gebirgsbärbel


2 Answers

You can use the following:

http://servername/todos/ GET list all todos
http://servername/users/ GET list all users
http://servername/users/{user_id}/ GET list an user
http://servername/users/{user_id}/todos/ GET list all todos for an user   

I think the point here is how you want to design the relationships between your resources, if a todo just can exist in the context of an user use a hierarchy like approach as above. As general rule i usually follow this:

Use path variables to encode hierarchy: /parent/child

Put punctuation characters in path variables to avoid implying hierarchy where none exists: /parent/child1;child2

Use query variables to imply inputs into an algorithm, for example: /search?q=jellyfish&start=20

like image 182
angvillar Avatar answered Nov 03 '22 05:11

angvillar


Having the username in the URL depends on what you want to do (if anything at all) when you receive a request where the username in the URL does not match the authentication. If you want to re-authorize the user in this situation then yes - it's OK to have the username in the URL, otherwise it's OK to have it just in your header or other authentication scheme if there is no such need.

One fairly common example of a valid requirement would be if you have to have a main user (or group of such users) that can impersonate other users.

like image 24
allu Avatar answered Nov 03 '22 07:11

allu