背景信息分析:
根据 RFC 2616,第 9.5 条,POST 用于创建资源:
使用 POST 方法要求原始服务器接受请求中包含的实体作为请求-URI 在请求线中识别的资源的新子属。
根据 RFC 2616,第 9.6 条,PUT 用于创建或取代资源:
PUT 方法要求关闭的实体存储在提供的请求-URI. 如果请求-URI 提到已经存在的资源,关闭的实体 SHOULD 将被视为居住在原始服务器的修改版本. 如果请求-URI 没有指向现有资源,并且 URI 能够由请求用户年龄定义为新资源。
我的问题:
那么,哪种HTTP方法应该用于创建资源?或者两者都应该得到支持?
Create => HTTP PUT
Retrieve => HTTP GET
Update => HTTP POST
Delete => HTTP DELETE
事实上, CRUD 操作的 R(选择) 和 D(选择) 可以直接地图到 HTTP 方法 GET 和 DELETE 相应。 然而,混淆在 C(现实) 和 U(更新) 操作中。 在某些情况下,可以使用 PUT 为创建而在其他情况下需要 POST。
基于上述定义,我的使用 HTTP PUT 方法与使用 HTTP POST 方法为 REST 服务是: 使用 HTTP PUT 方法,当:
The client includes all aspect of the resource including the unique identifier to uniquely identify the resource. Example: creating a new employee.
The client provides all the information for a resource to be able to modify that resource.This implies that the server side does not update any aspect of the resource (such as an update date).
The server will provide some information concerning the newly created resource. For example, take a logging system. A new entry in the log will most likely have a numbering scheme which is determined on the server side. Upon creating a new log entry, the new sequence number will be determined by the server and not by the client.
On a modification of a resource, the server will provide such information as a resource state or an update date. Again in this case not all information was provided by the client and the resource will be changing from one modification request to the next. Hence a non idempotent operation.
结论
PUT 是用于创建或替换客户端所知道的 URL 的资源。
因此: PUT 仅是 CREATE 的候选人,客户在创建资源之前已经知道 URL。 /blogs/nigel/entry/when_to_use_post_vs_put 因为标题被用作资源密钥
RFC 如下:
注意: PUT 主要用于更新资源(通过将其全部替换为资源),但最近出现了使用 PATCH 来更新现有资源的动作,因为 PUT 说明它取代了整个资源。
從 REST API 設計 - 資源模型 Prakash Subramaniam of Thoughtworks
这迫使API避免多个客户更新一个资源的国家过渡问题,并且更顺利地与事件来源和CQRS相匹配。
REST 是一个非常高级别的概念,事实上,它甚至没有提到 HTTP!
如果你有任何疑问如何在HTTP中实施REST,你总是可以看看原子出版协议(AtomPub)的规格. AtomPub是由许多HTTP和REST灯台开发的HTTP的RESTful网页服务的标准,其中一些来自Roy Fielding,REST的发明家和(共同)HTTP的发明家。
事实上,你甚至可以直接使用 AtomPub. 虽然它来自博客社区,它没有任何限制博客: 这是一个通用协议,以便通过 HTTP 与自愿的(自愿的)资源集合相互作用。
以下是 AtomPub 對資源創造的說法(第 9.2 節):
要将会员添加到集合中,客户将 POST 请求发送到集合的 URI。