PUT与PATCH请求的幂等性

为什么说PUT操作是幂等的,而PATCH操作是非幂等的?

根据 RFC 2616 Section 9.1.2

什么是幂等性Wikipedia

简单来说就是一个操作无论执行多少次,都会得到相同的结果,即f(x)=f(f(x)).

Why

首先我们都知道PATCH是对资源的部分更新,PUT是对资源的整体更新。
现在该资源是一个集合。

  1. 假设现在请求GET /users,返回users的集合。
    [{ "id": 1, "username": "firstuser", "email": "firstuser@example.org" }]

  2. 现在我们发送请求PATCH /users,进行更新操作(为该集合添加一个元素)
    [{ "username": "newuser", "email": "newuser@example.org" }]

  3. 再次请求GET /users
    [{ "id": 1, "username": "firstuser", "email": "firstuser@example.org" }, { "id": 2, "username": "newuser", "email": "newuser@example.org" }]

  4. 重复第二步操作,现在的结果(假设用户名可重复):
    [{ "id": 1, "username": "firstuser", "email": "firstuser@example.org" }, { "id": 2, "username": "newuser", "email": "newuser@example.org" }, { "id": 3, "username": "newuser", "email": "newuser@example.org" }]

    如果Patch请求是f(x),那么此时f(x)!=f(f(x)),即patch是非幂等的。

而此时如果请求的是PUT ,那么应该更新整个资源,即整个集合。所以PUT是幂等的。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值