/Products/123
每个产品在后端数据库中都有一个关联的供应商实体. POST和PUT请求必须指定供应商ID,然后使用该ID从数据库中获取供应商实体.
如果用户发布了PUT / Products / 123,但是包含错误的供应商ID,那么应该返回什么?
404找不到指定找不到哪个资源的消息?
409冲突?
404
状态代码可能不是正确的选择,因为尚未找到的资源不是您的请求的目标:
07001
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.
409
状态代码可能适合这种情况,但不是最佳选择(我不会将此情况定义为冲突):
07003
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
状态代码:
07005
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 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.
在选择最合适的4xx状态代码时,下图(摘自this page)非常有见地: