未找到子实体的正确HTTP状态码是什么?

问题描述:

说我有一个资源未找到子实体的正确HTTP状态码是什么?

/Products/123 

而且每个Product在后台数据库相关的Supplier实体。 POST和PUT请求必须指定供应商ID,然后用它从数据库中提取供应商实体。

如果用户发出PUT /Products/123什么应返回,这是发现,但包括不良供应商ID,这是

404 Not Found带有指定找不到哪个资源的消息?

409 Conflict

+1

你有没有考虑'422'? –

404状态代码可能不是正确的选择,因为一直没有找到的资源是不是你要求的目标:

6.5.4. 404 Not Found

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. A 404 status code does not indicate whether this lack of representation is temporary or permanent; the 410 (Gone) status code is preferred over 404 if the origin server knows, presumably through some configurable means, that the condition is likely to be permanent.

409状态代码可能是适合这种情况,但不是最好的选择(我不会定义这种情况下作为冲突):

6.5.8. 409 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. [..]

我会去422状态码有明显的DES cription在响应有效载荷:

11.2. 422 Unprocessable Entity

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.

下图(从this page萃取)是相当有见地的,当涉及到采摘最适宜4xx状态码:

Picking the right 4xx status code

我不相信有一个正确答案这个问题(除非一些REST纯粹可以提供一些线索),但我们目前使用(或滥用...)HTTP 400(错误请求)与一个额外的HTTP标题说明错误(即X错误:供应商ID无效)。但HTTP 422也是一个很好的选择。因为是指定的响应是关于子资源没有明确的方法 以下状态404或409将会造成混乱。

+0

将404与一个消息有效载荷一起返回,表明类似“没有找到ID为999的供应商”,从而消除混淆也是可以接受的吗? – BCA

+1

@BCA总是欢迎响应有效负载中的消息,使事情变得清晰。无法找到请求的资源时,“404”是合适的。在这种情况下,请求的资源(ID为123的产品)存在并且可以找到,但请求有效负载(包含无效数据)存在问题。因此,对错误进行很好描述的'422'会很好。 –

你好我会使用404如前所述:

6.5.4. 404 Not Found

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. A 404 status code does not indicate whether this lack of representation is temporary or permanent; the 410 (Gone) status code is preferred over 404 if the origin server knows, presumably through some configurable means, that the condition is likely to be permanent.

因为你正在寻找存在的产品,但供应商ID没有,所以基本上就像是我们在不同的城市找你,你的存在,但不是在城市,所以我们会说,嘿,我们做了找不到你。

我相信供应商和产品他们有一种关系,这是一种很难的关系,如果你没有该产品的供应商,产品就不存在,所以这意味着你不能更新产品不知道它是供应商。