REST API最佳实践:在哪里放置参数? [英] REST API Best practices: Where to put parameters?

查看:317
本文介绍了REST API最佳实践:在哪里放置参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

REST API可以至少有两种方式使用参数:


  1. 作为URL路径的一部分 / api / resource / parametervalue

  2. 作为查询参数(即 / api / resource?parameter = value

这里最好的做法是什么?有没有使用1和何时使用2的一般准则?



现实世界的例子:Twitter使用查询参数来指定间隔。 ( http://api.twitter.com/1/statuses/home_timeline.json?since_id=12345&max_id=54321



将这些参数放在URL路径中是否认为更好的设计?

解决方案

如果有最佳记录实践中,我还没有找到它们。但是,以下是确定在url中放置参数的几个指导方针:



可选参数往往更容易放入查询字符串。 >

如果要在参数值与现有资源不对应时返回404错误,那么我将趋向于路径段参数。例如 / customer / 232 其中232不是有效的客户ID。



如果您想要返回一个空列表那么当没有找到参数时,我建议使用查询字符串参数。例如 / contacts?name = dave



如果参数影响到您的URI空间的整个子树,那么使用路径段。例如一个语言参数 /en/document/foo.txt /document/foo.txt?language=en



我更喜欢唯一标识符在一个路径段而不是查询参数。



URI的官方规则是在此RFC规范中找到此处。另外还有一个非常有用的RFC规范 here 定义了URI参数化的规则。


A REST API can have parameters in at least two ways:

  1. As part of the URL-path (i.e. /api/resource/parametervalue )
  2. As a query argument (i.e. /api/resource?parameter=value )

What is the best practice here? Are there any general guidelines when to use 1 and when to use 2?

Real world example: Twitter uses query parameters for specifying intervals. (http://api.twitter.com/1/statuses/home_timeline.json?since_id=12345&max_id=54321)

Would it be considered better design to put these parameters in the URL path?

解决方案

If there are documented best practices, I have not found them yet. However, here are a few guidelines I use when determining where to put parameters in an url:

Optional parameters tend to be easier to put in the query string.

If you want to return a 404 error when the parameter value does not correspond to an existing resource then I would tend towards a path segment parameter. e.g. /customer/232 where 232 is not a valid customer id.

If however you want to return an empty list then when the parameter is not found then I suggest using query string parameters. e.g. /contacts?name=dave

If a parameter affects an entire subtree of your URI space then use a path segment. e.g. a language parameter /en/document/foo.txt versus /document/foo.txt?language=en

I prefer unique identifiers to be in a path segment rather than a query parameter.

The official rules for URIs are found in this RFC spec here. There is also another very useful RFC spec here that defines rules for parameterizing URIs.

这篇关于REST API最佳实践:在哪里放置参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆