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": "[email protected]" }]

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

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

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

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

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

猜你喜欢

转载自blog.csdn.net/Jack_PJ/article/details/102726816