当消费者发送不正确的请求时,Web 服务应该响应哪个 HTTP 错误代码?

Which HTTP Error code should a Web Service respond with when the consumer sends an incorrect request?

假设您在 Python/Flask 中有一个采用以下请求正文的 REST 服务:

{'date': '2015-01-01'}

您的消费者发送了以下不正确的请求:

{'date': '01/01/2015'}.

您的 API 无法解析它,并且您已捕获错误并知道用户以错误的格式发送了日期。您响应哪个 HTTP 错误代码?

我一直在使用 HTTP Code 400:

The request could not be understood by the server due to malformed syntax. The client SHOULD NOT repeat the request without modifications.

我已经告诉我的消费者,如果他看到 400,他不应该尝试重新发送请求,因为它需要先更改。

但是,我的消费者报告说,我的网络服务器有时会返回 400 错误,其中包含以下 HTML:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>400 Bad Request</title>
<h1>Bad Request</h1>
<p>The browser (or proxy) sent a request that this server could not understand.</p>

有时我的用户会收到此错误消息,即使是有效请求,我仍然无法弄清楚。现在我想知道我对 400 的使用是否不正确。值得注意的是,他不能单独使用 HTTP 代码来告诉他是否应该重新发送。

您可以使用状态代码 400422 并在响应负载中提供一些额外的提示。例如:

{
  "errors": [
    {
      "field": "date",
      "message": "The format of the date must 'MM/dd/yyyy'"
    }
  ]
}

这样,最终用户就会知道其请求中的错误并进行更新。

希望对你有帮助, 蒂埃里