我的目标是创建幂等/创建作为 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/