RESTful API best practices for admin and normal user access

眉间皱痕 提交于 2019-12-11 12:35:27

问题


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?


回答1:


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.




回答2:


The user identifier should not be a part of the uri as the user retrieving the resource has no relation to the resource being retrieved. When there is a parent child relation between the resources, you typically include them in the uri.

The user's access to the resource in your case should be deduced from the authorization token that they send with the request.



来源:https://stackoverflow.com/questions/35070866/restful-api-best-practices-for-admin-and-normal-user-access

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!