Skip to content

Handling POST, PUT, PATCH & DELETE Requests

Mastering Data Modification: POST, PUT, PATCH, and DELETE Requests

Section titled “Mastering Data Modification: POST, PUT, PATCH, and DELETE Requests”

This chapter delves into sending data to servers and modifying resources using HTTP methods like POST, PUT, PATCH, and DELETE with the Python requests library. We’ll explore how to send different types of data, such as form data and JSON payloads.

The POST method is typically used to create a new resource on the server. With requests, you can make a POST request using requests.post(). You can send data in various formats, most commonly as form data or JSON.

To send data as application/x-www-form-urlencoded (like an HTML form submission), pass a dictionary to the data parameter:

import requests
# We'll use httpbin.org, a useful service for testing HTTP requests.
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 echoes the data it received in the 'form' field of the JSON response.
print("Response JSON:")
print(response.json())
Status Code: 200
Response 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"
}

For modern APIs, sending data as application/json is very common. requests makes this easy with the json parameter. It automatically serializes your Python dictionary to a JSON string and sets the Content-Type header to 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 echoes the JSON data it received in the 'json' field.
print("Response JSON:")
print(response.json())
Status Code: 200
Response 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
},
"origin": "your.ip.address",
"url": "https://httpbin.org/post"
}

Always check response.status_code to ensure your request was successful (e.g., 201 Created for a successful POST). You can access the response content using response.text (for raw text) or response.json() (if the response is JSON).

The PUT method is typically used to completely replace an existing resource or create it if it doesn’t exist at the specified URL. The requests.put() method works similarly to requests.post(), allowing data or json parameters.

import requests
# Assume a resource exists at /put for user_id 123
url = 'https://httpbin.org/put' # httpbin.org/put echoes the PUT data
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())
Status Code: 200
Response 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"
}

A successful PUT request usually returns a 200 OK (if an existing resource was updated) or 201 Created (if a new resource was created). Some APIs might return 204 No Content if the update was successful and there’s no body to return.

The PATCH method is used for making partial modifications to an existing resource. Unlike PUT, you only send the data for the fields you want to change. The requests.patch() method facilitates this.

import requests
url = 'https://httpbin.org/patch' # httpbin.org/patch echoes the PATCH data
update_data = {
'email': 'jane.doe.new@example.com' # Only updating the email
}
response = requests.patch(url, json=update_data)
print(f"Status Code: {response.status_code}")
print("Response JSON:")
print(response.json())
Status Code: 200
Response 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"
}

A successful PATCH request typically returns a 200 OK or 204 No Content. Using JSON for PATCH requests is common, as it clearly defines the fields to be modified.

The DELETE method is used to remove a resource identified by a URL. The requests.delete() method is used for this. DELETE requests typically do not have a request body, as the resource to be deleted is specified in the URL.

import requests
# Assume we want to delete resource with id 789
# Note: httpbin.org/delete will reflect the deletion request but doesn't actually store/delete state.
url = 'https://httpbin.org/delete?id=789'
response = requests.delete(url)
print(f"Status Code: {response.status_code}")
# Often, a successful DELETE returns an empty body or a confirmation message.
# httpbin.org/delete echoes the request details.
print("Response JSON:")
print(response.json()) # Will show args, headers, etc.
Status Code: 200
Response JSON:
{
"args": {
"id": "789"
},
"data": "",
"files": {},
"form": {},
"headers": { ... },
"json": null,
"origin": "your.ip.address",
"url": "https://httpbin.org/delete?id=789"
}

A successful DELETE request commonly returns a 200 OK (often with a confirmation message or the deleted resource representation) or 204 No Content (indicating success with no response body). While requests allows sending a body with DELETE (e.g., using data or json parameters), it’s less common and depends on the specific API design.

To understand HTTP methods in more depth, refer to the MDN Web Docs on HTTP request methods: https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods

Practice using these methods with public APIs like JSONPlaceholder (https://jsonplaceholder.typicode.com/) which provides fake API endpoints for testing.