兩者的區別:
PATCH:更新部分資源,非冪等,非安全
PUT:更新整個資源,具有冪等性,非安全
注:
冪等性:多次請求的結果和請求一次的結果一樣
安全性:請求不改變資源狀態
舉個兩者明顯區別的例子(我對兩者定義的理解):
查詢資源列表
request: GET /users response: [ { "id": 1 "name": "xx" "description": "test xx", "phone": "127" } ]
這時候提供個接口,支持修改名稱和描述
第一種:接口的HTTP方法定義為PUT:
request: PUT /users/1 { "name": "yy" }
查詢資源列表
request: GET /users response: [ { "id": 1 "name": "yy" "description": null, "phone": "127" } ]
第二種:接口的HTTP方法定義為PATCH:
request: PATCH /users/1 { "name": "yy" }
查詢資源列表
request: GET /users response: [ { "id": 1 "name": "yy" "description": "test xx", "phone": "127" } ]
然后還有一個疑問:在上面的場景,PUT和PATCH都是具有冪等性的,為什么說PATCH非冪等的?
實際上,關於PATCH在定義中,還有另一種場景:通過PATCH發送一系列指令,並通過OP表示操作類型
PATCH /users [ { "op": "add", "path": "/", "value": { "name": "zz", "description": "test zz", "phone": "128" } }, { "op": "replace", "path": "/1", "value": { "name": "yy" } } ]
查詢資源列表
request: GET /users response: [ { "id": 1 "name": "yy" "description": "test xx", "phone": "127" }, { "id": 2 "name": "zz" "description": "test zz", "phone": "128" } ]
op表示對資源的操作,總共有六種:add,replace,remove,move,copy,test
以上的例子都是按照PATCH與PUT的規定,進行舉例,實際的的結果,是要根據代碼邏輯來,就像有些人用POST方法去修改名稱,只是說不規范,不是說不行。
參考:
https://stackoverflow.com/questions/28459418/rest-api-put-vs-patch-with-real-life-examples