处理 POST、PUT、PATCH 和 DELETE 请求
掌握数据修改:POST、PUT、PATCH 和 DELETE 请求
Section titled “掌握数据修改:POST、PUT、PATCH 和 DELETE 请求”本章深入探讨如何使用 Python requests 库向服务器发送数据以及使用 POST、PUT、PATCH 和 DELETE 等 HTTP 方法修改资源。我们将探索如何发送不同类型的数据,例如表单数据和 JSON 有效载荷(payloads)。
使用 POST 创建资源
Section titled “使用 POST 创建资源”POST 方法通常用于在服务器上创建新资源。使用 requests,你可以通过 requests.post() 发起 POST 请求。你可以发送各种格式的数据,最常见的是表单数据或 JSON。
发送表单数据
Section titled “发送表单数据”要以 application/x-www-form-urlencoded 格式发送数据(类似于 HTML 表单提交),请将一个字典传递给 data 参数:
import requests
# 我们将使用 httpbin.org,这是一个用于测试 HTTP 请求的有用服务。url = 'https://httpbin.org/post'payload_form = { 'name': 'John Doe', 'email': 'john.doe@example.com'}
response = requests.post(url, data=payload_form)
print(f"Status Code: {response.status_code}")# httpbin.org/post 会在其 JSON 响应的 'form' 字段中回显它收到的数据。print("Response JSON:")print(response.json())输出(示例)
Section titled “输出(示例)”Status Code: 200Response JSON:{ "args": {}, "data": "", "files": {}, "form": { "email": "john.doe@example.com", "name": "John Doe" }, "headers": { ... }, "json": null, "origin": "your.ip.address", "url": "https://httpbin.org/post"}发送 JSON 数据
Section titled “发送 JSON 数据”对于现代 API,以 application/json 格式发送数据非常常见。requests 通过 json 参数使其变得简单。它会自动将你的 Python 字典序列化为 JSON 字符串,并设置 Content-Type 头部为 application/json。
import requests
url = 'https://httpbin.org/post'payload_json = { 'product_id': 12345, 'quantity': 2, 'preferences': {'color': 'blue', 'size': 'large'}}
response = requests.post(url, json=payload_json)
print(f"Status Code: {response.status_code}")# httpbin.org/post 会在其 'json' 字段中回显它收到的 JSON 数据。print("Response JSON:")print(response.json())输出(示例)
Section titled “输出(示例)”Status Code: 200Response JSON:{ "args": {}, "data": "{\"product_id\": 12345, \"quantity\": 2, \"preferences\": {\"color\": \"blue\", \"size\": \"large\"}}", "files": {}, "form": {}, "headers": { "Content-Type": "application/json", ... }, "json": { "preferences": { "color": "blue", "size": "large" }, "product_id": 12345, "quantity": 2 },\n "origin": "your.ip.address", "url": "https://httpbin.org/post"}始终检查 response.status_code 以确保你的请求成功(例如,成功的 POST 通常返回 201 Created)。你可以使用 response.text(获取原始文本)或 response.json()(如果响应是 JSON 格式)来访问响应内容。
使用 PUT 更新/替换资源
Section titled “使用 PUT 更新/替换资源”PUT 方法通常用于完全替换现有资源,或者在指定 URL 不存在时创建该资源。requests.put() 方法的工作方式与 requests.post() 类似,允许使用 data 或 json 参数。
import requests
# 假设在 /put 路径下存在 user_id 123 的资源url = 'https://httpbin.org/put' # httpbin.org/put 会回显 PUT 数据user_data = { 'name': 'Jane Doe', 'email': 'jane.doe@example.com', 'status': 'active'}
response = requests.put(url, json=user_data)
print(f"Status Code: {response.status_code}")print("Response JSON:")print(response.json())输出(示例)
Section titled “输出(示例)”Status Code: 200Response JSON:{ "args": {}, "data": "{\"name\": \"Jane Doe\", \"email\": \"jane.doe@example.com\", \"status\": \"active\"}", "files": {}, "form": {}, "headers": { "Content-Type": "application/json", ... }, "json": { "email": "jane.doe@example.com", "name": "Jane Doe", "status": "active" }, "origin": "your.ip.address", "url": "https://httpbin.org/put"}成功的 PUT 请求通常返回 200 OK(如果更新了现有资源)或 201 Created(如果创建了新资源)。如果更新成功且没有要返回的响应体,某些 API 可能会返回 204 No Content。
使用 PATCH 部分更新资源
Section titled “使用 PATCH 部分更新资源”PATCH 方法用于对现有资源进行部分修改。与 PUT 不同,你只需发送要更改字段的数据。requests.patch() 方法提供了便利。
import requests
url = 'https://httpbin.org/patch' # httpbin.org/patch 会回显 PATCH 数据update_data = { 'email': 'jane.doe.new@example.com' # 只更新邮箱}
response = requests.patch(url, json=update_data)
print(f"Status Code: {response.status_code}")print("Response JSON:")print(response.json())输出(示例)
Section titled “输出(示例)”Status Code: 200Response JSON:{ "args": {}, "data": "{\"email\": \"jane.doe.new@example.com\"}", "files": {}, "form": {}, "headers": { "Content-Type": "application/json", ... }, "json": { "email": "jane.doe.new@example.com" }, "origin": "your.ip.address", "url": "https://httpbin.org/patch"}成功的 PATCH 请求通常返回 200 OK 或 204 No Content。在 PATCH 请求中使用 JSON 很常见,因为它可以清晰地定义要修改的字段。
使用 DELETE 删除资源
Section titled “使用 DELETE 删除资源”DELETE 方法用于删除通过 URL 标识的资源。使用 requests.delete() 方法执行此操作。DELETE 请求通常没有请求体,因为要删除的资源是在 URL 中指定的。
import requests
# 假设我们要删除 ID 为 789 的资源# 注意:httpbin.org/delete 会反映删除请求,但它实际上不会存储或删除状态。url = 'https://httpbin.org/delete?id=789'
response = requests.delete(url)
print(f"Status Code: {response.status_code}")# 通常,成功的 DELETE 请求会返回一个空响应体或确认消息。# httpbin.org/delete 会回显请求详情。print("Response JSON:")print(response.json()) # 将显示 args、headers 等输出(示例)
Section titled “输出(示例)”Status Code: 200Response JSON:{ "args": { "id": "789" }, "data": "", "files": {}, "form": {}, "headers": { ... }, "json": null, "origin": "your.ip.address", "url": "https://httpbin.org/delete?id=789"}成功的 DELETE 请求通常返回 200 OK(通常包含确认消息或被删除资源的表示)或 204 No Content(表示成功但没有响应体)。虽然 requests 允许在 DELETE 请求中发送请求体(例如,使用 data 或 json 参数),但这不太常见,取决于具体的 API 设计。
要更深入地理解 HTTP 方法,请参考 MDN Web Docs 关于 HTTP 请求方法的内容:https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods
可以使用 JSONPlaceholder (https://jsonplaceholder.typicode.com/) 等公共 API 来练习使用这些方法,它提供了用于测试的虚假 API 接口。