简体   繁体   English

RESTful API体系结构约定:如何传递参数

[英]RESTful API architecture conventions: How should parameters be passed

I have some questions about the best way I should allow parameters to be passed to a RESTful API that I program. 我有一些关于我应该允许参数传递给我编程的RESTful API的最佳方法的问题。

Eg I want to retrieve information about a user: API call with method GET would be: /api/users/ 例如,我想检索有关用户的信息:使用方法GET的API调用将是: /api/users/
Should the id be passed in the url /api/users/5 or as actual GET data /api/users/?id=5 id应该在url /api/users/5传递还是作为实际的GET数据/api/users/?id=5

From what I've read and concluded myself I would tend to go for option one (pass the parameter in the url) as it seems more intuitive and very clean. 从我自己阅读并得出的结论来看,我倾向于选择一个(通过url中的参数),因为它看起来更直观,更干净。

That option however would be difficult for more elaborate queries. 然而,对于更复杂的查询,该选项将是困难的。 Example: get user by age or last login date or even nested queries (get all posts from user 5). 示例:按年龄或上次登录日期获取用户甚至嵌套查询(获取用户5的所有帖子)。 For these use cases it would be much more convient to pass data as request parameters since those would contain key value pairs that can be easily identified ( /api/users/?age=20 ) 对于这些用例,将数据作为请求参数传递会更加方便,因为它们包含可以轻松识别的键值对( /api/users/?age=20

I'd be interested in your opinion: 我对你的意见感兴趣:
Which is the better way to go here and why? 哪个更好的方式去这里,为什么?
If you prefer option 2: How should the parameters be structured ideally? 如果您更喜欢选项2:如何理想地构建参数?

Both are applicable 两者都适用

GET /api/users/5 returns the user with ID 5. GET /api/users/?age=20 returns the group of users whose age is 20. GET /api/posts/?user_id=5 returns the group of posts by user 5. GET /api/users/5返回ID为5的用户GET /api/users/?age=20返回年龄为20的用户组GET /api/posts/?user_id=5返回帖子组用户5。

Typically ID is a special case, in that it identifies the resource. 通常,ID是一种特殊情况,因为它标识资源。 You wouldn't search for users by an ID - you just get the one you want. 您不会通过ID搜索用户 - 您只需获得所需的用户。

Keep in mind that for REST, the whole URI, including the query string, is an atomic identifier to the resource. 请记住,对于REST,整个URI(包括查询字符串)是资源的原子标识符。 There's no better or worse, as long as the URI always identifies the same resource and is being provided by the service, not constructed by the client. 没有更好或更糟的,只要URI始终标识相同的资源并且由服务提供,而不是由客户端构造。

In that sense, /api/users/5 isn't any more or less RESTful than /api/users?id=5 , but they refer to different things. 从这个意义上说, /api/users/5并不比/api/users?id=5更多或更少RESTful,但它们指的是不同的东西。 When you consider the URI semantics, using the parameters for querying collections of resources, /api/users/5 identifies a single user resource, while /api/users?id=5 identifies a collection of users, filtered by id, with a single element result. 当您考虑URI语义时,使用参数查询资源集合, /api/users/5标识单个用户资源,而/api/users?id=5标识用户集合,按ID过滤,单个用户元素结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM