Designing URI for current logged in user in REST a

2019-01-21 19:11发布

问题:

I need a URI in my REST API to retrieve the current logged in user. Usually I use GET on resource with ID, but the client doesn't know the ID of the user.

I found the following solutions:

  • By user name

    This solution uses the user name instead of the ID of the user.

    Example:

    • Bitbucket REST API: GET /user/{userSlug}
  • With own resource

    This solution has one resource for users and one additional resource for logged in user.

    Examples:

    • JIRA REST API: GET /myself

    • GitHub REST API: GET /user

    • Stack Exchange REST API: GET /me

  • With symbolic link

    This solution has a symbolic link for the ID of the user.

    Example:

    • Confluence REST API: GET /user/current
  • With filter

    This solution uses a filter for the user name.

    Example:

    • JIRA REST API: GET /user?username={username}

Which one is most RESTful? What are the pros and cons?

回答1:

It's up to you. All the approaches are perfectly fine from a REST perspective.

According to Roy Thomas Fielding's dissertation*, any information that can be named can be a resource:

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. [...]

When using /me, /users/me, /users/myself, /users/current and similars, you have a locator for the authenticated user and it will always identify the concept of an authenticated user, regardless of which user is authenticated.

For more flexibility, you also can support /users/{username}.

By the way, a similar situation was addressed in Is using magic (me/self) resource identifiers going against REST principles?


* If you are interested in REST, the chapter 5 of Fielding's dissertation is a must-read.



回答2:

All are equally RESTful. REST is not about URIs, it is about using them RESTfully.

REST is about the client navigating application state. Part of this state may be who is the current user. All URLs can be used to get this part of application state.



标签: rest http url