Should resource ids be present in urls?

2019-06-27 12:04发布

In situations where the resource id can be identified by other means (such as current_user for pages that require authentication), is it a good idea to omit the id from the url? (For example, /students/1/homework to /students/homework).

Also, would this have any impact on the restfulness of the urls? I am suspecting it does for HTTP verbs, but for custom actions I am not so sure.

3条回答
神经病院院长
2楼-- · 2019-06-27 12:43

URLs should always point to one specific resource. They can either be absolute or relative. Think of it as a filesystem. In some cases (security/scalability) you can't allow listings.

  • Session-based / Relative resources /students/me, /students/latest, /students/latest/homework/lastest
  • Absolute resources /students/3, /students/3/homework, /teachers/3/homework/3
查看更多
做自己的国王
3楼-- · 2019-06-27 12:48

I suppose it is down to your application and what is useful for clients to see. If your connecting user is an admin who can see all students homework, then the /students/1/homework path makes sense, however if it will only ever be students using this resource then the /students/homework makes more sense.
Essentially the latter could be thought of as a namespace for all student resources.
I have found it very useful to split these resources by namespaces as to not confuse client writers and keep your authorisation very clear (who can see/do what).

查看更多
小情绪 Triste *
4楼-- · 2019-06-27 12:52

In your example, the 2 URIs identify different resources:

  • the homework of user #1,
  • the homework of the current user.

The choice depends a lot on which resource you think people will want to refer to (by e-mail or by bookmark for example).

I don't think the second solution is unRESTful, but I would prefer the first one, since it is compatible with a lot of additional features (e.g. teachers could access the representation of students' homework).

查看更多
登录 后发表回答