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

查看:36
本文介绍了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 规范这里定义了参数化 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天全站免登陆