背景信息分析:
根据 RFC 2616,第 9.5 条,POST 用于创建资源:
使用 POST 方法要求原始服务器接受请求中包含的实体作为请求-URI 在请求线中识别的资源的新子属。
根据 RFC 2616,第 9.6 条,PUT 用于创建或取代资源:
PUT 方法要求关闭的实体存储在提供的请求-URI. 如果请求-URI 提到已经存在的资源,关闭的实体 SHOULD 将被视为居住在原始服务器的修改版本. 如果请求-URI 没有指向现有资源,并且 URI 能够由请求用户年龄定义为新资源。
我的问题:
那么,哪种HTTP方法应该用于创建资源?或者两者都应该得到支持?
在恢复已经提到的风险下,似乎很重要的是要记住,PUT意味着客户端在创建资源时会控制什么URL。因此,PUT和POST之间的选择的一部分将是关于您可以信任客户端提供正确的,正常的URL,与您的URL计划是什么相一致。
当您无法完全信任客户端做正确的事情时,更适合使用 POST 创建一个新的项目,然后将 URL 返回客户端在回复中。
我想添加我的“实用”建议. 使用 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
雖然可能有一種有趣的方式來描述這些,但它似乎與從答案到網站的不同聲明相矛盾。
如果您是使用 Web API 的.NET 开发人员,事实是(从 Microsoft API 文档), http://www.asp.net/web-api/overview/creating-web-apis/creating-a-web-api-that-supports-crud-operations:
1. PUT = UPDATE (/api/products/id)
2. MCSD Exams 2014 - UPDATE = PUT, there are **NO** multiple answers for that question period.
确保您可以使用“POST”更新,但只需跟随与您提供的框架的协议。在我的情况下,它是.NET / Web API,所以PUT是为了更新,没有讨论。
我希望这有助于任何微软开发人员阅读所有评论与亚马逊和Sun/Java网站链接。
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.
结论
原始服务器可以使用此 URI 创建资源
所以你使用POST和可能,但不需要PUT为资源创建. 你不需要支持两者. 对于我来说,POST是完美的足够。
如您的引用所提到的,您使用 PUT 创建没有资源分配到 IRI,您希望创建一个资源无论如何. 例如, PUT /users/123/password 通常将旧密码替换为新密码,但您可以使用它创建一个密码,如果它已经不存在(例如,由新鲜注册的用户或通过恢复被禁止的用户)。