未找到的子实体的正确HTTP状态代码是什么? [英] What is the correct HTTP status code for a child entity that is not found?
问题描述
说我有资源
/ Products / 123
每个产品
都有一个关联的供应商
后端数据库中的实体。 POST和PUT请求必须指定供应商ID,然后用于从数据库中获取供应商实体。
如果用户发出 PUT / Products / 123
,应该返回什么,是找到,但包含错误的供应商ID,不?
404 Not Found
带有指定未找到哪个资源的消息?
409冲突
?
Say I've got a resource
/Products/123
And each Product
has an associated Supplier
entity in the back end database. POST and PUT requests must specify a supplier ID, which is then used to fetch a Supplier entity from the database.
What should be returned if a user issues a PUT /Products/123
, which is found, but includes a bad Supplier ID, which is not?
404 Not Found
with a message specifying which resource wasn't found?
409 Conflict
?
The 404
status code may not be right choice because the resource that has not been found is not the target of your request:
The
404
(Not Found) status code indicates that the origin server did not find a current representation for the target resource or is not willing to disclose that one exists. A404
status code does not indicate whether this lack of representation is temporary or permanent; the410
(Gone) status code is preferred over404
if the origin server knows, presumably through some configurable means, that the condition is likely to be permanent.
The 409
status code might be suitable for this situation, but is not be the best choice (I wouldn't define this situation as a conflict):
The
409
(Conflict) status code indicates that the request could not be completed due to a conflict with the current state of the target resource. This code is used in situations where the user might be able to resolve the conflict and resubmit the request. The server SHOULD generate a payload that includes enough information for a user to recognize the source of the conflict. [..]
I would go for 422
status code with a clear description in the response payload:
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.
The following diagram (extracted from this page) is pretty insightful when it comes to picking the most suitable 4xx
status code:
这篇关于未找到的子实体的正确HTTP状态代码是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!