什么是 正确的 HTTP 状态返回 当我执行 POST 请求以创建新用户,但其中一个参数不正确时 - 数据库中不存在我包含在用户数据中的公司 ID。
邮政
数据:{用户名:'newuser',年龄:99,公司 ID:34 }
数据库中不存在 ID 为 34 的公司。
我在想这是否可能是:
最佳答案
400
或 422
首先,请记住它是 client error ,所以 5xx
状态代码不适合这里。你应该选择一个 4xx
然后状态码。
最明显的选项是 400
和 422
:
400
. 422
表示服务器无法处理请求实体。 请参阅以下来自 RFC 4918 的引用(对于您的情况,只需在显示 XML 时读取 JSON):
11.2. 422 Unprocessable Entity
The
422
(Unprocessable Entity) status code means the server understands the content type of the request entity (hence a415
(Unsupported Media Type) status code is inappropriate), and the syntax of the request entity is correct (thus a400
(Bad Request) status code is inappropriate) but was unable to process the contained instructions. For example, this error condition may occur if an XML request body contains well-formed (i.e., syntactically correct), but semantically erroneous, XML instructions.
此 answer 中解决了类似的情况。 .
例如,GitHub API v3也返回
422
如果有效负载的内容包含无效值(但在语法上有效):There are three possible types of client errors on API calls that receive request bodies:
Sending invalid JSON will result in a
400 Bad Request
response. [...]Sending the wrong type of JSON values will result in a
400 Bad Request response
. [...]Sending invalid fields will result in a
422 Unprocessable Entity
response. [...]
Michael Kropat拼凑一个set of diagrams在选择最合适的状态代码时,这是非常有见地的。
4xx
见下图状态代码:关于rest - POST 数据不正确时的 HTTP 状态(使用不存在的资源 ID),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50643217/