[英]Should I put a user id in a REST url or get it from authentication
I'm building a RESTful api with Express.js.我正在用 Express.js 构建一个 RESTful api。 Let's say I have some Users
which own Resources
.假设我有一些拥有Resources
Users
。 A good way to get the Resources
of a specific User
would be: GET /users/:user_id/resources
.获取特定User
Resources
的一个好方法是: GET /users/:user_id/resources
。
I implemented authentication for the api and can thus get the user_id
from req.user.user_id
instead of from the url.我为 api 实现了身份验证,因此可以从req.user.user_id
而不是从 url 获取user_id
。 This means I could just use GET /resources
to get the resources from the authenticated user.这意味着我可以只使用GET /resources
resources 从经过身份验证的用户那里获取资源。
My question: is this good practice and why (or why not)?我的问题:这是好的做法吗?为什么(或为什么不)?
I think, it is bad practice.我认为,这是不好的做法。 Resources should return all resources, not filtered in any way.资源应该返回所有资源,没有以任何方式过滤。 I would say it is better to have an additional endpoint /user/resources
.我会说最好有一个额外的端点/user/resources
。 In this way responses will be:通过这种方式,响应将是:
/users/15/resources
- will give resources for user 15 if allowed or 403. /users/15/resources
- 如果允许或 403,将为用户 15 提供资源。/user/resources
- will give resources for the authenticated user (if I am user 15, then this gives the same response as in 1.) OR 404 OR 403. /user/resources
- 将为经过身份验证的用户提供资源(如果我是用户 15,那么这将提供与 1 中相同的响应。)或 404 或 403。/resources
- will give not filtered resources (if it is prohibited, then just don't create this endpoint, or return only public resources). /resources
- 将提供未过滤的资源(如果被禁止,则不要创建此端点,或仅返回公共资源)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.