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

19 篇文章 0 订阅
6 篇文章 0 订阅

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值