rest - 在 REST API 中使 PUT 创建请求幂等

标签 rest http put idempotent

我的目标是创建幂等/创建作为 PUT 动词实现的 REST API。

Idempotent RFC 状态:

Idempotent methods are distinguished because the request can be
repeated automatically if a communication failure occurs before the
client is able to read the server's response. For example, if a
client sends a PUT request and the underlying connection is closed
before any response is received, then the client can establish a new
connection and retry the idempotent request. It knows that repeating the request will have the same intended effect, even if the original
request succeeded, though the response might differ.

PUT RFC状态:

If the target resource does not have a current representation and the PUT successfully creates one, then the origin server MUST inform the
user agent by sending a 201 (Created) response. If the target
resource does have a current representation and that representation
is successfully modified in accordance with the state of the enclosed representation, then the origin server MUST send either a 200 (OK) or a 204 (No Content) response to indicate successful completion of the
request.

假设/create 将创建的资源存储在数据库中,第一次创建时是否应该返回 201,重试/create 时是否应该返回 200? 是否应该重试/create 将相同的资源重新存储在数据库中以符合 PUT RFC?

最佳答案

所以这个问题有点困惑。让我们看看能否解决这个问题。

PUT /create

abcde

粗略地说:用表示abcde替换/create的状态。换句话说,消息的语义类似于

store(key => "/create", value => "abcde")

请注意,处理该消息两次与处理该消息一次产生的效果相同。

store(key => "/create", value => "abcde")
store(key => "/create", value => "abcde")

请注意,我们对此处使用的 key 非常具体; PUT 与目标资源的状态相关; PUT/create 是一条请求我们修改 /create 的消息,而不是请求我们创建一些其他资源。

Assuming that /create stores the created resource in DB, should it return 201 on first creation and 200 on retried /create?

是的。

Should retried /create store the same resource in DB all over again to conform with PUT RFC?

如果资源已经具有请求的表示,则无需再次存储它。

关于rest - 在 REST API 中使 PUT 创建请求幂等,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47855826/

相关文章:

子资源的API设计?

具有多部分发布请求的 Ruby Sinatra

rest - 使用 grails.plugins.rest.client.RestResponse 获取 img/png

iphone - http头请求中的UDID iphone

java - 使用捕获的数据包从服务器向应用程序发送 http 响应

api - RSPEC - PUT 请求返回错误 405

c# AspNetCore WebApi - 如何判断 PUT 上是否设置了 json 属性?

python - 对 django tastypie 资源的 PUT 请求不起作用

java - "MediaType.APPLICATION_JSON"的注释类型 Produces 的属性值未定义

java - 使用 Tomcat 7 javax/inject/Singleton 部署 JAX-RS (Jersey 2.13) Web 服务