背景信息分析:

根据 RFC 2616,第 9.5 条,POST 用于创建资源:

使用 POST 方法要求原始服务器接受请求中包含的实体作为请求-URI 在请求线中识别的资源的新子属。

根据 RFC 2616,第 9.6 条,PUT 用于创建或取代资源:

PUT 方法要求关闭的实体存储在提供的请求-URI. 如果请求-URI 提到已经存在的资源,关闭的实体 SHOULD 将被视为居住在原始服务器的修改版本. 如果请求-URI 没有指向现有资源,并且 URI 能够由请求用户年龄定义为新资源。

我的问题:

那么,哪种HTTP方法应该用于创建资源?或者两者都应该得到支持?


当前回答

POST 用于将数据发送到服务器. PUT 用于将数据存入服务器上的资源(例如,文件)。

我看到这一点在一个脚本(第55页)从书HTTP: The Definitive Guide。

其他回答

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.

结论

在很简单的方式,我正在采取Facebook时间线的例子。

案例1:当你在时间表上发布某些东西时,这是一个新鲜的新输入,所以在这种情况下,他们使用POST方法,因为POST方法是无效的。

案例2:如果你的朋友第一次评论你的帖子,它也会在数据库中创建一个新的帖子,以便使用POST方法。

案例3:如果你的朋友编辑他的评论,在这种情况下,他们有一个评论 ID,所以他们将更新一个现有评论而不是创建一个新的数据库输入。

在单行中,使用 POST 在数据库中添加一个新的输入和 PUT 在数据库中更新一些东西。

使用 POST 创建,而 PUT 更新,这就是 Ruby on Rails 如何做到这一点。

PUT    /items/1      #=> update
POST   /items        #=> create

以最简单的方式解释:

POST 做它所说的, POST 意味着它提出了一个新的对象创建的请求. MDN 提到这一点为“其他副作用”,一个例子是增加指数(“POST”这个词意味着什么)。

PUT可以被认为是更新现有数据对象,当人们说它可以用于添加对象,这是因为它可以从现有父母对象更新儿童零值。

MDN 方法 PUT 文档

POST 用于将数据发送到服务器. PUT 用于将数据存入服务器上的资源(例如,文件)。

我看到这一点在一个脚本(第55页)从书HTTP: The Definitive Guide。