RESTFUL服务中POST/PUT/PATCH方法的区别

来源:互联网 发布:mac iphoto可以删除吗 编辑:程序博客网 时间:2024/06/06 09:42

经常会混淆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

原创粉丝点击