POST时HTTP状态,数据不正确(使用不存在的资源ID) [英] HTTP status while POST with incorrect data (using id of resource which does not exist)
问题描述
当我执行POST请求以创建新用户时,要返回的正确HTTP状态是什么,但是其参数之一不正确-用户数据中包含的公司ID数据库中不存在.
What would be the correct HTTP status to return when I am performing the POST request to create a new user, but one of its parameters is incorrect - the company id I am including with the user data doesn't exist in the database.
开机自检 数据:{username:"newuser",年龄:99, company_id:34 }
POST data: {username: 'newuser', age: 99, company_id: 34}
数据库中不存在ID为34的公司.
我在想是否可以:
- 400,一种无效数据,但它是有效的,但ID不存在
- 404-但不清楚哪个资源不存在
- 409,因为这是一种冲突,用户可以通过更改公司ID来解决该问题
- 422?
- 或500-因为这是一种数据库错误,而那里不存在不存在的ID,
推荐答案
400
或422
首先,请紧记这是客户端错误,因此 5xx
状态代码在这里不合适.然后,您应该选择 4xx
状态代码.
400
or 422
First of all, keep in min that it's a client error, so 5xx
status codes are not suitable here. You should pick a 4xx
status code then.
最明显的选项是 400
和
The most obvious options are 400
and 422
:
- 如果JSON在语法上无效,则返回
400
. - 如果JSON在语法上有效,但其内容无效,则返回
- If the JSON is syntactically invalid, return
400
. - If JSON is syntactically valid but its content is invalid, return
422
to indicate that the request entity cannot be processed by the server.
请参见 RFC 4918 中的以下引文(针对您的情况,请阅读 JSON 表示 XML ):
See the following quote from the RFC 4918 (for your situation, just read JSON when it says XML):
422
(不可处理实体)状态代码表示服务器
了解请求实体的内容类型(因此
415
(不受支持的媒体类型)状态代码不合适),并且
请求实体的语法正确(因此400
(错误请求)
状态代码不正确),但无法处理其中包含的内容
指示.例如对于如果XML可能会出现此错误情况
请求正文包含格式正确(即语法正确)的内容,但
语义错误的XML指令.
The 422
(Unprocessable Entity) status code means the server
understands the content type of the request entity (hence a
415
(Unsupported Media Type) status code is inappropriate), and the
syntax of the request entity is correct (thus a 400
(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.
此答案也解决了类似情况.
出于示例目的, GitHub API v3 也返回 422
:>
For example purposes, the GitHub API v3 also returns 422
if the content of the payload contains invalid values (but is syntactically valid):
API调用中可能存在三种类型的客户端错误, 接收请求正文:
There are three possible types of client errors on API calls that receive request bodies:
-
发送无效的JSON将导致
400 Bad Request
响应. [...]
Sending invalid JSON will result in a
400 Bad Request
response. [...]
发送错误类型的JSON值将导致400 Bad Request response
. [...]
Sending the wrong type of JSON values will result in a 400 Bad Request response
. [...]
发送无效字段将导致422 Unprocessable Entity
响应. [...]
Sending invalid fields will result in a 422 Unprocessable Entity
response. [...]
Michael Kropat 组合了
Michael Kropat put together a set of diagrams that's pretty insightful when it comes to picking the most suitable status code. See the following diagram for 4xx
status codes:
这篇关于POST时HTTP状态,数据不正确(使用不存在的资源ID)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!