Why is PUT operation idempotent, while PATCH operation is non-idempotent?
According to RFC 2616 Section 9.1.2
What is idempotence Wikipedia
Simply put, no matter how many times an operation is executed, it will get the same result, that is, f(x)=f(f(x)) .
Why
First of all, we all know that PATCH is a partial update of resources, and PUT is an overall update of resources.
Now the resource is a collection.
-
Suppose you request now
GET /users
and return a collection of users.
[{ "id": 1, "username": "firstuser", "email": "[email protected]" }]
-
Now we send a request
PATCH /users
to update (add an element to the collection)
[{ "username": "newuser", "email": "[email protected]" }]
-
Request again
GET /users
[{ "id": 1, "username": "firstuser", "email": "[email protected]" }, { "id": 2, "username": "newuser", "email": "[email protected]" }]
-
Repeat the second step, the current result (assuming the user name can be repeated):
[{ "id": 1, "username": "firstuser", "email": "[email protected]" }, { "id": 2, "username": "newuser", "email": "[email protected]" }, { "id": 3, "username": "newuser", "email": "[email protected]" }]
If the patch request is f(x), then f(x)!=f(f(x)), that is, the patch is non-idempotent.
At this time, if the request is PUT, then the entire resource, that is, the entire collection, should be updated. So PUT is idempotent.