背景信息分析:

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

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

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

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

我的问题:

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


当前回答

以最简单的方式解释:

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

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

MDN 方法 PUT 文档

其他回答

您可以在网页上找到声明说

也不是很正确。


最好选择 PUT 和 POST 之间,基于行动的可行性。

PUT 意味着放置一个资源 - 完全取代在特定 URL 上可用的任何东西与不同的东西. 根据定义,一个 PUT 是无能为力. 尽量尽量多次,结果是相同的. x=5 是无能为力. 你可以 PUT 一个资源,无论它以前存在,还是不存在(例如,创建,或更新)!

POST 更新一个资源,添加一个子资源,或引发一个变化. 一个 POST 不是 idempotent,因此 x++ 不是 idempotent。


根据这个论点,PUT是为了创建,当你知道你将创建的东西的URL。POST可以用来创建,当你知道“工厂”的URL或管理者为你想要创建的东西类别。

如:

POST /expense-report

或:

PUT  /expense-report/10929

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

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

两者都用于客户端到服务器之间的数据传输,但它们之间存在微妙的差异,即:

PUT POST
Replacing existing resource or creating if resource is not exist. www.example.com/com/customer/{customerId} www.example.com/com/customer/123/order/{orderId} Identifier is chosen by the client. Creating new resources and subordinate resources, e.g. a file is subordinate to a directory containing it or a row is subordinate to a database table. www.example.com/com/customer/ www.example.com/com/customer/123/order/ identifier is returned by server
Idempotent i.e. if you PUT a resource twice, it has no effect. Example: Do it as many times as you want, the result will be same. x=1; POST is neither safe nor idempotent. Example: x++;
Works as specific Works as abstractive
If you create or update a resource using PUT and then make that same call again, the resource is still there and still has the same state as it did with the first call. Making two identical POST requests will most likely result in two resources containing the same information.

类似:

PUT 即采取并放置它在哪里. POST 如发送邮件在邮局。

此分類上一篇

社交媒体/网络分析:

社交媒体上的帖子:当我们发布消息时,它会创建新的帖子(即编辑)我们已经发布的帖子。

大多数时候,你会用它们如下:

POST a resource into a collection PUT a resource identified by collection/:id。

例如:

POST /items PUT /items/1234

请注意,POST在收藏中“创建”一个新的元素,而PUT在某个URL中“替换”一个元素,但使用PUT进行部分修改是一种非常常见的做法,也就是说,只使用它来更新现有资源,并仅修改体内所包含的字段(忽略其他字段)。

请记住,REST是一组条约和指导方针,以保持您的API简单。 如果您结束了一个复杂的工作周围,只需检查“RESTfull”框,那么您正在击败目的。

这里是一个简单的规则:

到一个 URL 的 PUT 应该用于更新或创建可以位于该 URL 的资源。

POST to a URL should be used to update or create a resource that is located at some other ("subordinate") URL, or is not locatable via HTTP. URL 应该用于更新或创建位于某个其他(“下级”) URL 或无法通过 HTTP 找到的资源。