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



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

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

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

Accept: text/plain; charset=utf-8

现在,除了url之外,媒体类型可以根据RFC 2046接受参数,并且可以在无处不在的text/html; charset=utf-8audio/*; q=0.2Accept标头中看到。它还显示了供应商制作的MIME类型可以定义自己的参数,如:

application/vnd.example-com.foo+json; version=1.0
application/vnd.example-info.bar+xml; version=2.0

因此,对于以前注册的MIME类型,如text/htmlapplication/json,是否可以为应用程序的需要包含自定义参数?例如:

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

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

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.

这是否意味着如果客户端识别出text/plain介质类型的footnotes=true参数将是不合格的?

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

Accept报头参数属于响应的打包。

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

查询参数属于所寻址的资源。

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

David Eyk说得对。

如果您正在更改返回的实体,它应该在URI中。其他任何东西都会破坏缓存等。

然而,URI中的"format"大多是错误的。如果可以,请使用Accept。响应头已经准备好了,可以提供一个平稳的运行。

然而,如果你不能使用Accept(就像在一个标准的web浏览器中),我建议使用DOS扩展或类似的来覆盖Accept。

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

最新更新