中从当前用户返回数据

中从当前用户返回数据

本文介绍了如何设计 URL 以在 REST API 中从当前用户返回数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个基于 REST 的服务,用户可以在其中返回他们自己的书籍列表(这是一个私人列表).

I have a REST based service where a user can return a list of their own books (this is a private list).

当前网址为 ../api/users/{userId}/books

每次调用时,他们还将提供之前提供的身份验证令牌.

With each call they will also be supplying an authentication token supplied earlier.

我的问题是:

  1. 在 URL 中提供 userId 是多余的吗?当我们在每次调用时获得一个令牌时,我们可以找出正在执行调用的用户并返回他们的书籍列表.userId 不是严格要求的.

  1. Is supplying the userId in the URL redundant? As we get a token with each call we can find out which user is performing the call and return their list of books. The userId is not strictly required.

删除 userId 是否会违反 REST 原则,因为 /users/books/ 看起来应该返回所有用户的所有书籍?

Would removing the userId break REST principles as /users/books/ looks like it should return all books for all users?

我是否应该硬着头皮对令牌进行身份验证,然后检查令牌是否属于同一userId?

Should I just bite the bullet and authenticate them against the token and then check that the token belongs to the same userId?

推荐答案

简短回答

您可以在 URL 中使用 me 来引用当前用户.使用这种方法,您将获得如下 URL:/users/me/books.

Short answer

You could use me in the URL to refer to the current user. With this approach, you would have a URL as following: /users/me/books.

在 URL 中提供 userId 是多余的吗?当我们在每次调用时获得一个令牌时,我们可以找出哪个用户正在执行调用并返回他们的书籍列表.userId 不是严格要求的.

你可以考虑做这样的事情:/users/me/books.其中me 指的是当前用户.比/users/books更容易理解,可以用来返回用户的所有书籍.

You could consider doing something like this: /users/me/books. Where me refers to the current user. It's easier to understand than /users/books, which can be used to return all books from the users.

为了获得一些灵活性,除了 /users/me/books,您还可以支持 /users/{userId}/books.

For some flexibility, besides /users/me/books, you could support /users/{userId}/books.

URL /users/me 可用于返回当前用户的数据.许多 API,例如 StackExchangeFacebook, SpotifyGoogle+ 采用这种方法.

The URL /users/me can be used to return data from the current user. Many APIs, such as StackExchange, Facebook, Spotify and Google+ adopt this approach.

删除 userId 是否会违反 REST 原则,因为 /users/books/ 看起来应该返回所有用户的所有书籍?

我不认为它会违反任何 REST 原则,但我认为您的资源不会被正确识别.正如我在上面回答的那样,我会使用 /users/me/books 并支持 /users/{userId}/books.

I don't think it will break any REST principles, but I think your resources will not be properly indetified. As I answered above, I would use /users/me/books and also support /users/{userId}/books.

我是否应该硬着头皮对令牌进行身份验证,然后检查令牌是否属于同一个 userId?

当在 URL 中使用 userId 向用户请求私人信息时,检查令牌是否属于包含在 userId 中的用户没有坏处网址.

When using the userId in the URL to request private information from a user, there's no harm in checking if the token belongs to the user with the userId included in the URL.

这篇关于如何设计 URL 以在 REST API 中从当前用户返回数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 18:21