Making a POST request in Python is most commonly done using the requests library, which is a powerful and user-friendly HTTP client. For asynchronous applications, httpx is a great choice. You can also use the built-in urllib.request module, but it's generally more verbose.
Let's explore the most common methods.
1. Using the requests Library (Recommended)
The requests library simplifies HTTP requests significantly. If you don't have it installed, do so first:
pip install requests
Here's how to make a POST request with various types of data:
1.1 Basic POST with Form-Encoded Data
This is common for submitting HTML form data. The data parameter expects a dictionary, and requests will automatically url-encode it and set the Content-Type header to application/x-www-form-urlencoded.
import requests
url = "https://httpbin.org/post" # A service that echoes POST requests
# Data to send (form-encoded)
payload = {
'name': 'John Doe',
'age': 30,
'city': 'New York'
}
try:
response = requests.post(url, data=payload)
# Check if the request was successful (status code 200)
response.raise_for_status() # Raises an HTTPError for bad responses (4xx or 5xx)
print(f"Status Code: {response.status_code}")
print(f"Response Text (usually JSON from httpbin): {response.text}")
print("\n--- Parsed JSON Response ---")
print(response.json()) # Parse JSON response
except requests.exceptions.HTTPError as errh:
print(f"Http Error: {errh}")
except requests.exceptions.ConnectionError as errc:
print(f"Error Connecting: {errc}")
except requests.exceptions.Timeout as errt:
print(f"Timeout Error: {errt}")
except requests.exceptions.RequestException as err:
print(f"Something went wrong: {err}")
Output Explanation (from httpbin.org/post):
The httpbin.org/post service will return a JSON object containing:
args: Query parameters (if any).
data: The raw request body as a string.
files: Uploaded files (if any).
form: The parsed form-encoded data (what you sent in data).
headers: All request headers that were sent.
json: The parsed JSON data (if you sent json instead of data).
origin: Your IP address.
url: The URL you requested.
You'll see your name, age, and city inside the form key.
1.2 POST with JSON Data
This is very common for APIs. The json parameter expects a dictionary, and requests will automatically serialize it to JSON and set the Content-Type header to application/json.
import requests
url = "https://httpbin.org/post"
# Data to send (JSON)
json_payload = {
'product_id': 'XYZ-123',
'name': 'Laptop',
'price': 1200.00,
'features': ['16GB RAM', '512GB SSD']
}
try:
response = requests.post(url, json=json_payload)
response.raise_for_status()
print(f"Status Code: {response.status_code}")
print("\n--- Parsed JSON Response ---")
# httpbin will put your JSON payload under the 'json' key in its response
print(response.json())
except requests.exceptions.RequestException as e:
print(f"An error occurred: {e}")
You'll see your product_id, name, price, and features inside the json key of the response.
1.3 POST with Custom Headers
You often need to send custom headers, such as Authorization tokens, User-Agent, or specific Accept types.
import requests
url = "https://httpbin.org/post"
# Custom headers
headers = {
'User-Agent': 'MyPythonApp/1.0',
'Authorization': 'Bearer my_secret_token_123',
'Custom-Header': 'Hello-World'
}
payload = {'message': 'Hello from Python!'}
try:
response = requests.post(url, json=payload, headers=headers)
response.raise_for_status()
print(f"Status Code: {response.status_code}")
print("\n--- Sent Headers (echoed back from httpbin) ---")
print(response.json()['headers']) # httpbin echoes headers back
except requests.exceptions.RequestException as e:
print(f"An error occurred: {e}")
1.4 POST with File Uploads (Multipart Form Data)
For uploading files, use the files parameter. It expects a dictionary where keys are the field names and values are file-like objects, tuples, or strings.
import requests
url = "https://httpbin.org/post"
# Prepare data for upload
# Option 1: Open a file
# with open('my_document.txt', 'rb') as f: # 'rb' for read binary
# files = {'upload_file': f}
# response = requests.post(url, files=files)
# print(response.json())
# Option 2: Directly provide content (e.g., from memory)
# 'upload_file' is the field name
# ('filename.txt', content, 'content_type')
files_to_upload = {
'report': ('report.txt', 'This is the content of the report.', 'text/plain'),
'image': ('logo.png', b'binary_image_data_here', 'image/png') # For actual binary, read from file
}
# You can also send other form data along with files
other_data = {
'description': 'Monthly summary',
'category': 'Finance'
}
try:
response = requests.post(url, data=other_data, files=files_to_upload)
response.raise_for_status()
print(f"Status Code: {response.status_code}")
print("\n--- Parsed Files and Form Data (echoed from httpbin) ---")
print(response.json()['files']) # Your uploaded files
print(response.json()['form']) # Your other form data
except requests.exceptions.RequestException as e:
print(f"An error occurred: {e}")
1.5 Timeout and Other Parameters
requests.post() accepts many other useful parameters:
timeout: How many seconds to wait for the server to send data before giving up.
auth: For HTTP authentication (e.g., requests.post(url, auth=('user', 'pass'))).
params: For URL query parameters (e.g., ?key=value).
allow_redirects: Whether to follow redirects (default True).
verify: Whether to verify SSL certificates (default True). Set to False to ignore, but use with caution in production!
import requests
url = "https://httpbin.org/post"
payload = {'test': 'timeout_example'}
try:
response = requests.post(url, json=payload, timeout=5) # 5 seconds timeout
response.raise_for_status()
print(f"Success with timeout: {response.status_code}")
except requests.exceptions.Timeout:
print("The request timed out!")
except requests.exceptions.RequestException as e:
print(f"An error occurred: {e}")
1.6 Using requests.Session (For Multiple Requests)
If you're making multiple requests to the same host, a Session object can improve performance by reusing the underlying TCP connection and handling cookies automatically.
import requests
# Create a session object
with requests.Session() as session:
session.headers.update({'Accept': 'application/json'}) # Set common headers for the session
# First POST request
url1 = "https://httpbin.org/post"
data1 = {'item': 'apple', 'quantity': 10}
response1 = session.post(url1, json=data1)
response1.raise_for_status()
print(f"Response 1 Status: {response1.status_code}")
print(f"Response 1 JSON: {response1.json()['json']}")
# Second POST request, using the same session (and headers)
url2 = "https://httpbin.org/post"
data2 = {'item': 'orange', 'quantity': 5}
response2 = session.post(url2, json=data2)
response2.raise_for_status()
print(f"Response 2 Status: {response2.status_code}")
print(f"Response 2 JSON: {response2.json()['json']}")
# Any cookies set by the server would be automatically managed by the session
2. Using httpx (For Asynchronous Applications)
If you're working with asyncio or an async web framework (like FastAPI), httpx is the recommended library. It has a very similar API to requests.
First, install it:
pip install httpx
import httpx
import asyncio
async def make_async_post_request():
url = "https://httpbin.org/post"
json_payload = {
'async_product': 'Async Widget',
'async_price': 99.99
}
headers = {
'User-Agent': 'MyAsyncPythonApp/1.0'
}
try:
async with httpx.AsyncClient() as client:
response = await client.post(url, json=json_payload, headers=headers, timeout=10)
response.raise_for_status() # Raises an HTTPStatusError for bad responses
print(f"Async Status Code: {response.status_code}")
print("\n--- Async Parsed JSON Response ---")
print(response.json())
except httpx.HTTPStatusError as e:
print(f"HTTP Error: {e.response.status_code} - {e.response.text}")
except httpx.RequestError as e:
print(f"An error occurred while requesting {e.request.url!r}: {e}")
if __name__ == "__main__":
asyncio.run(make_async_post_request())
3. Using urllib.request (Built-in, More Verbose)
This module is built into Python, so no installation is needed. However, it's significantly more complex and less convenient than requests for most use cases.
import urllib.request
import urllib.parse
import json # For JSON encoding/decoding
url = "https://httpbin.org/post"
# 1. Sending Form-Encoded Data
print("--- urllib: Sending Form-Encoded Data ---")
form_data = {'name': 'Alice', 'occupation': 'Engineer'}
# Encode the dictionary into a URL-encoded string
encoded_data = urllib.parse.urlencode(form_data).encode('utf-8') # Must be bytes
try:
req = urllib.request.Request(url, data=encoded_data, method='POST')
# urllib automatically sets Content-Type to application/x-www-form-urlencoded
with urllib.request.urlopen(req) as response:
print(f"Status Code: {response.getcode()}")
response_data = response.read().decode('utf-8')
print(json.loads(response_data)['form']) # Parse JSON response
except urllib.error.URLError as e:
print(f"Error: {e.reason}")
except Exception as e:
print(f"An unexpected error occurred: {e}")
print("\n--- urllib: Sending JSON Data ---")
# 2. Sending JSON Data
json_data = {'item_id': 'abc-456', 'quantity': 100}
json_bytes = json.dumps(json_data).encode('utf-8') # Encode to bytes
try:
req = urllib.request.Request(url, data=json_bytes, method='POST')
# Manually set Content-Type for JSON
req.add_header('Content-Type', 'application/json')
with urllib.request.urlopen(req) as response:
print(f"Status Code: {response.getcode()}")
response_data = response.read().decode('utf-8')
print(json.loads(response_data)['json']) # Parse JSON response
except urllib.error.URLError as e:
print(f"Error: {e.reason}")
except Exception as e:
print(f"An unexpected error occurred: {e}")
Which method to choose?
requests: For 99% of synchronous HTTP requests. It's concise, readable, and handles many complexities for you.
httpx: For asynchronous HTTP requests, especially in asyncio applications or frameworks like FastAPI. It has a very similar API to requests.
urllib.request: Only if you cannot install external libraries, or for very basic, quick scripts where adding requests is overkill. It requires more manual handling of headers, encoding, and error checking.