我的 REST API 中需要一个 URI 来检索当前登录的用户。通常我使用 GET
在具有 ID 的资源上,但客户端不知道用户的 ID。
我找到了以下解决方案:
通过用户名
此解决方案使用用户名而不是用户 ID。
例子:
- Bitbucket REST API :
GET/user/{userSlug}
- Bitbucket REST API :
有自己的资源
此解决方案为用户提供一种资源,为登录用户提供一种额外资源。
例子:
JIRA REST API :
GET/myself
GitHub REST API :
获取/用户
Stack Exchange REST API :
GET/me
带符号链接(symbolic link)
此解决方案具有用户 ID 的符号链接(symbolic link)。
例子:
- Confluence REST API :
GET/user/current
- Confluence REST API :
带过滤器
此解决方案使用用户名过滤器。
例子:
- JIRA REST API :
GET/user?username={用户名}
- JIRA REST API :
哪个最符合 REST 风格?有什么优点和缺点?
最佳答案
由您决定。从 REST 的角度来看,所有方法都非常好。
根据 Roy Thomas Fielding 的论文*,任何可以命名的信息都可以是资源:
5.2.1.1 Resources and Resource Identifiers
The key abstraction of information in REST is a resource. Any information that can be named can be a resource: a document or image, a temporal service (e.g. "today's weather in Los Angeles"), a collection of other resources, a non-virtual object (e.g. a person), and so on. In other words, any concept that might be the target of an author's hypertext reference must fit within the definition of a resource. A resource is a conceptual mapping to a set of entities, not the entity that corresponds to the mapping at any particular point in time. [...]
使用/me
、/users/me
、/users/myself
、/users/current
时和类似的东西,你有一个定位器为 authenticated user 并且它将始终识别 authenticated user 的概念,无论哪个用户已通过身份验证.
为了更加灵活,您还可以支持/users/{username}
。
顺便说一句,Is using magic (me/self) resource identifiers going against REST principles? 中解决了类似的情况。
* 如果您对 REST 感兴趣,chapter 5 Fielding 的论文是必读的。
关于rest - 为 REST 应用程序中的当前登录用户设计 URI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36520372/