Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RESTful API best practices for admin and normal user access

Having to create a RESTful web service with admin and normal user access to resources (lets say cars), I would like to structure the Uri for the users as:

http://myhost/users/5/cars/2

But as admin user, I would like to access all cars like:

http://myhost/cars/51

Instead of the first I proposed, would you think that it's better to use just one Uri for cars, using filters for users, like:

http://myhost/cars/?user=5

To don't have 2 different Uris for the same resource? Do you have other suggestions?

like image 750
Patrizio Rullo Avatar asked Jan 28 '16 19:01

Patrizio Rullo


People also ask

Should I separate admin API?

You should NOT separate your API based on your clients' role! For a very simple reason. You will end up with code duplication, inconsistency and many other issues. If you want to make any separation you need to think about business domains and encapsulation.


1 Answers

Both of the following URLs are good, even for admin even for plain users. Auth-token should be in the HTTP session, so the server should be able to detect if the requester is admin or not.

http://myhost/cars returns a collection of cars. It's recommended that returned cars are filtered based on authorization. If I'm an admin I can see all cars. If I'm user #5 then probably I can see only my car. So both admin and plain user can use the same URL.

In the case of http://myhost/cars/?user=5 an explicit filter is applied where I'm interested in car for User #5 even if I'm somebody else. Probably I get an empty list because I'm not authorized to see any item. This URL is also OK.

http://myhost/cars/51 means that I want to access car #51 directly. Doesn't matter if I'm admin or not. Probably I'll get a 4XX message (what is XX is another debate) if I'm not authorized to see this entity.

like image 59
pcjuzer Avatar answered Nov 15 '22 04:11

pcjuzer