为什么说PUT操作是幂等的,而PATCH操作是非幂等的?
什么是幂等性Wikipedia
简单来说就是一个操作无论执行多少次,都会得到相同的结果,即f(x)=f(f(x)).
Why
首先我们都知道PATCH是对资源的部分更新,PUT是对资源的整体更新。
现在该资源是一个集合。
-
假设现在请求
GET /users
,返回users的集合。
[{ "id": 1, "username": "firstuser", "email": "firstuser@example.org" }]
-
现在我们发送请求
PATCH /users
,进行更新操作(为该集合添加一个元素)
[{ "username": "newuser", "email": "newuser@example.org" }]
-
再次请求
GET /users
[{ "id": 1, "username": "firstuser", "email": "firstuser@example.org" }, { "id": 2, "username": "newuser", "email": "newuser@example.org" }]
-
重复第二步操作,现在的结果(假设用户名可重复):
[{ "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是幂等的。