8

我的 RESTFul API 只能响应 JSON 编码的数据(即我所有的标头都有Content-Type: application/json)。如果请求的Accept标头不允许 JSON(例如,Accept: text/html),我应该返回什么?我应该400 Bad Request在正文中返回带有解释的 a,还是有针对此异常的更具体的状态代码?

请注意,这与不受支持的请求内容类型不同

4

2 回答 2

11

如果你想在语义上是正确的:

如果请求是 HTTP/1.0:

406 Not Acceptable 是正确的返回值,因为客户端可能无法处理不属于请求类型的响应。

在 HTTP/1.1 中,这仍然是“正确”的做法,但也有例外,

来自 RFC 2616 Sec 10.4.7

 Note: HTTP/1.1 servers are allowed to return responses which are
      not acceptable according to the accept headers sent in the
      request. In some cases, this may even be preferable to sending a
      406 response. User agents are encouraged to inspect the headers of
      an incoming response to determine if it is acceptable.

事实上,正如@Jack 所提到的,它发生的可能性非常低。为了完整起见,我只包括这个答案。

于 2013-02-22T15:10:38.600 回答
4

不要打扰。

在某些情况下,您的服务的消费者不会费心设置此标头,例如在使用PHPcURLfile_get_contents()在 PHP 中时。

如果您的 API 文档声明您的服务仅支持 JSON 输出,那应该已经足够了。

您还可以使用扩展来强制执行格式,例如分别用于 JSON 和 XML /path/to/resource.json?a=b/path/to/resource.xml?a=b

如果您希望支持多种输出格式并且Accept请求标头值不确定,则应定义默认输出格式。

于 2013-02-21T23:39:40.507 回答