URL查询参数或媒体类型参数(在Accept标头中)配置对HTTP请求的响应?

时间:2011-07-15 02:35:10

标签: api http rest mime-types mime

我正在设计一个可以使用各种格式进行响应的REST API,其中一种格式是纯文本格式,可以配置为显示或隐藏响应中的某些方面(例如章节标题或脚注)。这样做的传统方式是通过URL查询参数,以指示所需的响应类型和配置选项,例如:

http://api.example.com/foo-book/ch1/?format=text&headings=false&footnotes=true

但是,用于指示所需响应类型(而不是format=text URL查询参数)的更优雅的RESTful方式是使用Accept标头,例如:

Accept: text/plain; charset=utf-8

现在,除了网址之外,媒体类型还可以按照RFC 2046采用参数,如普遍存在的text/html; charset=utf-8Accept标题{@ 1}}中所示。供应商制作的MIME类型也可以shown定义自己的参数,如:

audio/*; q=0.2

因此,对于之前注册的MIME类型(如application/vnd.example-com.foo+json; version=1.0 application/vnd.example-info.bar+xml; version=2.0 text/html),是否可以为应用程序的需求包含自定义参数?例如:

application/json

这似乎是一个优雅的RESTful解决方案,但它似乎也会违反某些东西。 RFC 2046 §1说:

Accept: text/plain; charset=utf-8; headings=false; footnotes=true

请注意最后一句:

Parameters are modifiers of the media subtype, and as such do not
fundamentally affect the nature of the content.  The set of
meaningful parameters depends on the media type and subtype.  Most
parameters are associated with a single specific subtype.  However, a
given top-level media type may define parameters which are applicable
to any subtype of that type.  Parameters may be required by their
defining media type or subtype or they may be optional.  MIME
implementations must also ignore any parameters whose names they do
not recognize.

如果客户识别MIME implementations must also ignore any parameters whose names they do not recognize. 媒体类型的footnotes=true参数,这是否意味着客户不符合规定?

2 个答案:

答案 0 :(得分:12)

在我看来,区别应该如下:

接受标题参数与响应的打包有关。

  • 媒体类型(例如application/json
  • 字符编码(例如charset=utf-8
  • 结构(例如,指定“doctype”的供应商扩展程序; application/vnd.example-com.foo+json; version=1.0

查询参数与所处理的资源有关。

  • 组件(例如标题和脚注)
  • 可选功能(例如格式化)
  • 约束(特别是在处理一系列类似的资源时)

答案 1 :(得分:2)

David Eyk是对的。

如果要更改返回的实体,则应该在URI中。任何其他东西都会破坏各种各样的东西,如缓存等。

然而,URI中的“格式”大多是错误的。如果可以,请使用Accept。响应标头已经到位,以提供平稳的驾驶。

但是,如果你不能使用Accept(就像在标准的webbrowser中一样),我建议使用DOS扩展或类似的方法来覆盖Accept。

e.g.
/image (is the resource)
/image.jpg
/image.gif