Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
496 views
in Technique[技术] by (71.8m points)

api - REST API最佳实践:在何处放置参数? [关闭](REST API Best practices: Where to put parameters? [closed])

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

(REST API至少可以通过两种方式获取参数:)

  1. As part of the URL-path (ie /api/resource/parametervalue )

    (作为URL路径的一部分 (即/api/resource/parametervalue ))

  2. As a query argument (ie /api/resource?parameter=value )

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

What is the best practice here?

(这里的最佳做法是什么?)

Are there any general guidelines when to use 1 and when to use 2?

(是否有任何一般指导原则何时使用1以及何时使用2?)

Real world example: Twitter uses query parameters for specifying intervals.

(真实世界的例子:Twitter使用查询参数来指定间隔。)

( http://api.twitter.com/1/statuses/home_timeline.json?since_id=12345&max_id=54321 )

(( 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?

(将这些参数放在URL路径中会被认为是更好的设计吗?)

  ask by Kalle Gustafsson translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:

(但是,这里有一些我在确定将参数放入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.

(如果要在参数值与现有资源不对应时返回404错误,那么我会倾向于路径段参数。)

eg /customer/232 where 232 is not a valid customer id.

(例如/customer/232 ,其中232不是有效的客户ID。)

If however you want to return an empty list then when the parameter is not found then I suggest using query string parameters.

(但是如果你想返回一个空列表,那么当找不到参数时,我建议使用查询字符串参数。)

eg /contacts?name=dave

(例如/contacts?name=dave)

If a parameter affects an entire subtree of your URI space then use a path segment.

(如果参数影响URI空间的整个子树,则使用路径段。)

eg a language parameter /en/document/foo.txt versus /document/foo.txt?language=en

(例如语言参数/en/document/foo.txt/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 .

(URI的官方规则可在此RFC规范中找到 。)

There is also another very useful RFC spec here that defines rules for parameterizing URIs.

(此处还有另一个非常有用的RFC规范它定义了参数化URI的规则。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...