web123456

About the difference between PATCH and PUT

The difference between the two:
PATCH: Update some resources, non-idempotent, non-safe
PUT: Update the entire resource, withIdepotency, non-safe
Note:
Impotence: The result of multiple requests is the same as the result of once requested
Security: Requests do not change the resource state

Let me give you an example of the obvious difference between the two (my understanding of the definitions of the two):

Query resource list

request:
GET /users
response:
[
    {
        "id": 1
        "name": "xx"
        "description": "test xx",
        "phone": "127"
    }
]

At this time, an interface is provided to support the modification of the name and description

The first type: The HTTP method of the interface is defined as PUT:

request:
PUT /users/1
{
    "name": "yy"
}

Query resource list

request:
GET /users
response:
[
    {
        "id": 1
        "name": "yy"
        "description": null"phone": "127"
    }
]

The second type: The HTTP method of the interface is defined as PATCH:

request:
PATCH /users/1
{
    "name": "yy"
}

Query resource list

request:
GET /users
response:
[
    {
        "id": 1
        "name": "yy"
        "description": "test xx""phone": "127"
    }
]

Then there is another question: In the above scenario, both PUT and PATCH are idempotent, why is it said that PATCH is not idempotent?
In fact, there is another scenario in the definition of PATCH: sending a series of instructions through PATCH and representing the operation type through OP

PATCH /users
[
    { 
        "op": "add", 
        "path": "/", 
        "value": {
            "name": "zz",
            "description": "test zz""phone": "128"
        }
    },
    { 
        "op": "replace", 
        "path": "/1", 
        "value": {
            "name": "yy"
        }
    }
]

Query resource list

request:
GET /users
response:
[
    {
        "id": 1
        "name": "yy"
        "description": "test xx""phone": "127"
    },
    {
        "id": 2
        "name": "zz"
        "description": "test zz""phone": "128"
    }
]

Op represents the operation of resources, there are six types: add, replace, remove,move,copy,test

The above examples are all given examples according to the regulations of PATCH and PUT. The actual result is to be based on the code logic. Just like some people use the POST method to modify the name, it just says that it is not standardized, not that it is not possible.

 

refer to:
/questions/28459418/rest-api-put-vs-patch-with-real-life-examples