The idempotence of PUT and PATCH requests

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.

  1. Suppose you request now GET /usersand return a collection of users.
    [{ "id": 1, "username": "firstuser", "email": "[email protected]" }]

  2. Now we send a request PATCH /usersto update (add an element to the collection)
    [{ "username": "newuser", "email": "[email protected]" }]

  3. Request againGET /users
    [{ "id": 1, "username": "firstuser", "email": "[email protected]" }, { "id": 2, "username": "newuser", "email": "[email protected]" }]

  4. 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.

Guess you like

Origin blog.csdn.net/Jack_PJ/article/details/102726816