资源已存在时 POST 的 HTTP 响应代码 [英] HTTP response code for POST when resource already exists

查看:41
本文介绍了资源已存在时 POST 的 HTTP 响应代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个允许客户端存储对象的服务器.这些对象完全在客户端构建,并带有在对象的整个生命周期内都是永久的对象 ID.

I'm building a server that allows clients to store objects. Those objects are fully constructed at client side, complete with object IDs that are permanent for the whole lifetime of the object.

我已经定义了 API,以便客户端可以使用 PUT 创建或修改对象:

I have defined the API so that clients can create or modify objects using PUT:

PUT /objects/{id} HTTP/1.1
...

{json representation of the object}

{id} 是对象 ID,因此它是请求 URI 的一部分.

The {id} is the object ID, so it is part of the Request-URI.

现在,我也在考虑允许客户端使用 POST 创建对象:

Now, I'm also considering allowing clients to create the object using POST:

POST /objects/ HTTP/1.1
...

{json representation of the object, including ID}

由于 POST 的意思是追加"操作,如果对象已经存在,我不确定该怎么做.我应该将请求视为修改请求还是应该返回一些错误代码(哪个)?

Since POST is meant as "append" operation, I'm not sure what to do in case the object is already there. Should I treat the request as modification request or should I return some error code (which)?

推荐答案

我的感觉是 409 Conflict 是最合适的,当然,在野外也很少见到:

My feeling is 409 Conflict is the most appropriate, however, seldom seen in the wild of course:

由于与资源的当前状态冲突,请求无法完成.仅在预期用户可能能够解决冲突并重新提交请求的情况下才允许使用此代码.响应主体应该包含足够的信息让用户识别冲突的来源.理想情况下,响应实体应包含足够的信息供用户或用户代理解决问题;然而,这可能是不可能的,也不是必需的.

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 entity would include enough information for the user or user agent to fix the problem; however, that might not be possible and is not required.

在响应 PUT 请求时最有可能发生冲突.例如,如果正在使用版本控制并且被 PUT 的实体包含对资源的更改,这些更改与之前(第三方)请求所做的更改相冲突,则服务器可能会使用 409 响应来指示它无法完成请求.在这种情况下,响应实体可能会以响应 Content-Type 定义的格式包含两个版本之间差异的列表.

Conflicts are most likely to occur in response to a PUT request. For example, if versioning were being used and the entity 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 entity would likely contain a list of the differences between the two versions in a format defined by the response Content-Type.

这篇关于资源已存在时 POST 的 HTTP 响应代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆