gpt4 book ai didi

http - 以 RESTful 方式递增资源计数器 : PUT vs POST

转载 作者:可可西里 更新时间:2023-11-01 15:05:29 24 4
gpt4 key购买 nike

我有一个带有计数器的资源。举个例子,我们称资源为profile,计数器是该资源的views数简介。

根据 REST wiki , PUT 请求应该用于资源创建或修改,并且应该是幂等的。如果我正在更新配置文件的名称,这种组合就很好,因为我可以发出 PUT 请求,将名称设置为某个值 1000 次,结果不会改变。

对于这些标准的 PUT 请求,我让浏览器执行如下操作:

PUT /profiles/123?property=value&property2=value2

为了递增计数器,可以这样调用 url:

PUT /profiles/123/?counter=views

每次调用都会导致计数器递增。从技术上讲,这是一个更新操作,但它违反了幂等性。

我正在寻找指导/最佳实践。您只是将其作为 POST 来执行吗?

最佳答案

我认为正确的答案是使用 PATCH。我没有看到其他人推荐它应该用于自动增加计数器,但我相信 RFC 2068说得很好:

The PATCH method is similar to PUT except that the entity contains alist of differences between the original version of the resourceidentified by the Request-URI and the desired content of the resourceafter the PATCH action has been applied. The list of differences isin a format defined by the media type of the entity (e.g.,"application/diff") and MUST include sufficient information to allowthe server to recreate the changes necessary to convert the originalversion of the resource to the desired version.

因此,要更新个人资料 123 的查看次数,我会:

PATCH /profiles/123 HTTP/1.1
Host: www.example.com
Content-Type: application/x-counters

views + 1

其中 x-counters 媒体类型(我刚刚编写的)由多行 field operator scalar 元组组成。 views = 500views - 1views + 3 在语法上都是有效的(但在语义上可能被禁止)。

我能理解有些人对另一种媒体类型的不满,但我谦虚地建议它比 POST/PUT 替代方案更正确。为一个字段创建一个资源,完成它自己的 URI,尤其是它自己的细节(我没有真正保留,我只有一个整数)对我来说听起来是错误和麻烦的。如果我要维护 23 个不同的计数器怎么办?

关于http - 以 RESTful 方式递增资源计数器 : PUT vs POST,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1426845/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com