背景信息分析:

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

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

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

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

我的问题:

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


当前回答

这里是一个简单的规则:

到一个 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 找到的资源。

其他回答

我想添加我的“实用”建议. 使用 PUT 当你知道“ID”可以恢复你正在储存的对象. 使用 PUT 不会工作太好,如果你需要, 说, 数据库创建的 ID 将被返回给你进行未来的搜索或更新。

因此: 保存现有用户,或者客户端创建 ID 的用户,并确认 ID 是独一无二的:

PUT /user/12345 HTTP/1.1  <-- create the user providing the id 12345
Host: mydomain.example

GET /user/12345 HTTP/1.1  <-- return that user
Host: mydomain.example

否则,使用 POST 首先创建对象,然后使用 PUT 更新对象:

POST /user HTTP/1.1   <--- create the user, server returns 12345
Host: mydomain.example

PUT /user/12345 HTTP/1.1  <--- update the user
Host: mydomain.example

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相匹配。

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

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 如发送邮件在邮局。

此分類上一篇

社交媒体/网络分析:

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

我认为还有一个有趣的点,没有在这个PUT vs POST问题上分享:

如果您想要一个没有JavaScript的Web应用程序(例如,如果有人使用一个命令线浏览器,如Lynx或一个浏览器插件,如NoScript或Mmatrix),您将不得不使用POST发送数据,因为HTML表单仅支持GET和POSTHTTP请求。

基本上,如果您想要使用逐步改进(https://en.wikipedia.org/wiki/Progressive_enhancement)让您的网页应用程序在任何地方工作,有和没有JavaScript,您无法使用其他HTTP方法,如PUT或DELETE,这些方法仅在HTTP版本1中添加。

POST: 使用它来创建新的资源. 它类似于 INSERT (SQL 声明) 具有自动增强 ID. 在回复部分中,它包含一个新生成的 ID。

POST 也用于更新记录。

PUT:使用它来创建一个新的资源,但在这里我知道身份密钥,它就像INSERT(SQL声明),在那里我提前知道身份密钥。

PUT 也用于更新资源