1. 程式人生 > >RESTFUL服務中POST/PUT/PATCH方法的區別

RESTFUL服務中POST/PUT/PATCH方法的區別

經常會混淆HTTP的POST/PUT方法,因為這兩個方法似乎都可以用來建立或更新一個資源。

區別是細微但清楚的:

POST方法用來建立一個子資源,如 /api/users,會在users下面建立一個user,如users/1

POST方法不是冪等的,多次執行,將導致多條相同的使用者被建立(users/1,users/2 ...而這些使用者除了自增長id外有著相同的資料,除非你的系統實現了額外的資料唯一性檢查)

而PUT方法用來建立一個URI已知的資源,或對已知資源進行完全替換,比如users/1,

因此PUT方法一般會用來更新一個已知資源,除非在建立前,你完全知道自己要建立的物件的URI。

下面是RFC的描述:

The fundamental difference between the POST and PUT requests is reflected in the different meaning of the Request-URI. 
The URI in a POST request identifies the resource that will handle the enclosed entity. 
That resource might be a data-accepting process, a gateway to some other protocol, or a separate entity that accepts annotations. 
In contrast, the URI in a PUT request identifies the entity enclosed with the request -- 
the user agent knows what URI is intended and the server MUST NOT attempt to apply the request to some other resource. 


PATCH方法是新引入的,是對PUT方法的補充,用來對已知資源進行區域性更新,參考 RFC 5789.

by iefreer