HTTP协议中的PUT、POST和PATCH方法有什么区别?


当前回答

PUT和PATCH w.r.t分别发送完整和部分数据进行替换/更新之间的差异非常符合逻辑。但是,我只提出以下几点

有时POST被认为是用于更新w.r.t PUT用于创建 HTTP是否要求/检查在PATCH中发送完整数据还是部分数据?否则PATCH可能与PUT/POST中的update完全相同

其他回答

这里是一个简单的描述:

POST总是用于创建资源(是否复制并不重要) PUT用于检查资源是否存在,然后更新,否则创建新的资源 PATCH总是用于更新资源

这样想吧……

POST - create

PUT -替换

补丁-更新

GET - read

DELETE -删除

最简单的解释:

创建新的记录

PUT -如果记录存在,更新else,创建一个新记录

补丁-更新

GET - read

DELETE -删除

下面的定义来自真实世界的例子。

示例概述 对于每个客户端数据,我们存储一个标识符来查找客户端数据,并将该标识符发送回客户端以供参考。

POST If the client sends data without any identifier, then we will store the data and assign/generate a new identifier. If the client again sends the same data without any identifier, then we will store the data and assign/generate a new identifier. Note: Duplication is allowed here. PUT If the client sends data with an identifier, then we will check whether that identifier exists. If the identifier exists, we will update the resource with the data, else we will create a resource with the data and assign/generate a new identifier. PATCH If the client sends data with an identifier, then we will check whether that identifier exists. If the identifier exists, we will update the resource with the data, else we will throw an exception.

注意:在PUT方法中,如果没有找到标识符,我们不会抛出异常。但是在PATCH方法中,如果没有找到标识符,则抛出异常。

如果您对上述内容有任何疑问,请告诉我。

你可能会把restful HTTP方法理解为javascript中对数组的相应操作(索引偏移量为1)。

请看下面的例子:

Method Url Meaning
GET /users return users array
GET /users/1 return users[1] object
POST /users users.push(body); return last id or index
PUT /users replace users array
PUT /users/1 users[1] = body
PATCH /users/1 users[1] = {...users[1], ...body }
DELETE /users/1 delete users[1]