api – HTTP 404是否为没有找到某些链接资源的PUT操作的适当响应?


PUT http://..../api/v1/events/456/attendees/789

如果任何事件#456或参加者#789不存在,返回HTTP 404是否正确(以及解释问题的详细错误有效负载,例如{“错误”:{“message”:“事件456不存在“,”代码“:”404“}}?


PUT http://..../api/v1/event
{ "location": 123, "name": "Party", "date": "2012-05-23", ...etc... }

如果位置#123不存在,返回404是否正确(以及响应中的细节)?如果没有,什么是合适的 – 只有400?

根据HTTP 1.1规范http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html

9.6 PUT … If the resource could not be created or modified with the Request-URI, an appropriate error response SHOULD be given that reflects the nature of the problem


不要太在意我这里的具体例子 – 它们是为了说明这一点而已.主要问题是:404是否因为没有找到链接的资源而失败的PUT操作的适当响应?

如果您可以指出参考文献,这将是非常好的 – 我很难找到达到这个细节水平的程度,也是非常可靠的.特别是关于REST API设计中资源关系的处理.

更新的想法我认为可能第一个例子应该返回404,第二个不应该.原因是在第一种情况下,我们添加的资源使用事件456和参加者789作为复合主键;第二个案例位置只是一个外键.在第二种情况下,应该返回一个错误,但不应该返回404 – 可能是412前提条件失败,或者可能只是一个400错误请求.思考?

有一些4xx HTTP status codes.最有可能是404或409:

404 Not Found

The server has not found anything matching the effective request URI.
No indication is given of whether the condition is temporary or
permanent. The 410 (Gone) status code SHOULD be used if the server
knows, through some internally configurable mechanism, that an old
resource is permanently unavailable and has no forwarding address.
This status code is commonly used when the server does not wish to
reveal exactly why the request has been refused, or when no other
response is applicable.

409 Conflict

The request could not be completed due to a conflict with the current
state of the resource. This code is only allowed in situations where
it is expected that the user might be able to resolve the conflict
and resubmit the request. The response body SHOULD include enough
information for the user to recognize the source of the conflict.
Ideally, the response representation would include enough information
for the user or user agent to fix the problem; however, that might
not be possible and is not required.

Conflicts are most likely to occur in response to a PUT request. For
example, if versioning were being used and the representation being
PUT included changes to a resource which conflict with those made by
an earlier (third-party) request, the server might use the 409
response to indicate that it can’t complete the request. In this
case, the response representation would likely contain a list of the
differences between the two versions.

这些都是合适的,但我想我会去409. 404被用于找不到URI,但409表示资源的当前状态不允许所请求的操作.在你的情况下,请求不能满足,因为某些东西是不允许的.


转载注明原文:api – HTTP 404是否为没有找到某些链接资源的PUT操作的适当响应?