Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

URI structure for restful API

I use basic authentication, so URI looks like http://test:[email protected]/.

If I want to give all users, I create an URI like http://test:[email protected]/users/

But what address should I use if I want to give a specific user? This should be

http://test:[email protected]/users/test/ 

or just

http://test:[email protected]/test/

or I don't know.

The reason that I am asking this question is that this type of authorization means that URI already contains username.

Thanks in advance.

like image 522
alexvassel Avatar asked Nov 18 '13 08:11

alexvassel


1 Answers

Creating a resource URI in a hierarchical fashion has the benefit that you won't have any id collisions. Your alternative version http://test:[email protected]/test/ could become problematic if you add another resource type (e.g. Role) with id test. You will have to ensure that your IDs are unique over all resource types and not only for a specific type. In addition: It's no longer clear, whether your resource URI points to an User or a Role.

And while it is not really required for REST it's one of the naming things that makes it easier for us humans to think about a REST API: "User Resources can be found in URIs containing the "users" label seems just so normal. REST itself is actually URI agnostic so it really shouldn't matter. But if you want to use meaningful (human-readable) URIs I would say

GET http://test:[email protected]/users/

will return all users.

POST http://test:[email protected]/users/ 

will create a new User and a new resource with an URI.

PUT http://test:[email protected]/users/test

will change the User resource identified with this URI and to fulfil reasonable expectations you should be able to get this user resource as

GET http://test:[email protected]/users/test

Last thing to consider: the authorised user might want to access the user resource for a different user (as unlikely as this scenario might currently seem):

GET http://another:[email protected]/users/test
like image 128
xwoker Avatar answered Nov 05 '22 23:11

xwoker