Pol*_*haw 62
根据HTTP规范:
PUT方法请求将所包含的实体存储在提供的Request-URI下.如果Request-URI引用已经存在的资源,则封闭的实体应该被视为驻留在源服务器上的实体的修改版本.如果Request-URI未指向现有资源,并且该URI能够被请求用户代理定义为新资源,则源服务器可以使用该URI创建资源.
因此,我认为使用PUT进行插入或更新是完全合法的,前提是在两种情况下都提前知道URI.如果您使用密钥作为URI的一部分(如http://www.somewhere.com/resources/k1中的 k1那样),则应该是这种情况.但是,为了理想地RESTful,对同一URL的GET也应该允许您下载资源.
我不认为这个操作可以被认为是RESTful,因为它做了两件事.它似乎提供了一个宏来满足特定客户的需求,而不是简单的数据访问.标准的RESTful设计将是
它不太明确,但我认为通过向http://www.somewhere.com/resources发送一个DELETE请求来删除所有资源也是合法的.
Y Y*_*Y Y 16
According to MDN Web Docs :
The HTTP PUT request method creates a new resource or replaces a representation of the target resource with the request payload.
The difference between PUT and POST is that PUT is idempotent: calling
it once or several times successively has the same effect (that is no
side effect), whereas successive identical POST requests may have
additional effects, akin to placing an order several times.
PUT /new.html HTTP/1.1
Run Code Online (Sandbox Code Playgroud)
PUT /new.html HTTP/1.1
Run Code Online (Sandbox Code Playgroud)
If the target resource does not have a current representation and the
PUT request successfully creates one, then the origin server must
inform the user agent by sending a 201 (Created) response.
PUT /new.html HTTP/1.1
Host: example.com
Content-type: text/html
Content-length: 16
<p>New File</p>
Run Code Online (Sandbox Code Playgroud)
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.
HTTP/1.1 201 Created
Content-Location: /new.html
Run Code Online (Sandbox Code Playgroud)
如果更新插入的定义是新记录与现有记录(要更新)的混合。
参考: https: //restfulapi.net/rest-put-vs-post/
PUT 需要是幂等的。这意味着如果您第二次 PUT 相同的有效负载,则系统状态不应更改。
如果预期的有效负载是新的和现有的混合,并且预期的行为是第二次创建更多新记录,那么“upsert”似乎会与 POST 更紧密地结合在一起。
我们努力创建容错 API。如果您无法使 PUT 幂等,而他们必须使用它,则可能会损坏系统。另一方面,POST 预计不会是幂等的,因此,如果您在有效负载中(一遍又一遍)发送仅更新数据(即使这在技术上违反了 POST 的幂等规则,因为它不会通过以下方式更改系统的状态):在后续调用中添加记录)系统(可能)不会被损坏。
如果你真的想实现 upsert,两者都不是完美的,但如果错误导致 PUT 上的损坏,则应归咎于 API(它应该是幂等的),而 POST 上的损坏是“我告诉过你了”。
我还喜欢思考 API 消费者会寻找什么。通常,在新屏幕上工作的 UI 开发人员会希望添加用户在 UI 中添加的记录。他将首先寻找 POST,然后发现它也处理等式的 PUT 方面。
所以,两者都不是,但如果必须选择,请选择 POST。
| 归档时间: |
|
| 查看次数: |
21493 次 |
| 最近记录: |