![]()
Python HTTPX: How to Send POST Requests
To send POST requests with Python HTTPX use the httpx.post() method and add the POST body and Content-Type using the data and headers parameters
import httpx
response = httpx.post("https://httpbin.org/post",
data={"key": "value"},
headers={"Content-Type": "application/json"},
)
print(response.json())
In this guide for The Python Web Scraping Playbook, we will look at how to make POST requests with the Python HTTPX library.
In this guide we will walk you through the most common ways of sending POST requests with Python HTTPX library:
- POST JSON Data Using Python HTTPX
- POST Form Data Using Python HTTPX
- Configuring Data Types
- Using POST Requests With Sessions
Let's begin...
Need help scraping the web?
Then check out ScrapeOps, the complete toolkit for web scraping.
POST JSON Data Using Python HTTPX
A common scenario for using POST requests is to send JSON data to an API endpoint, etc. Python HTTPX makes it straightforward to accomplish this task.
We simply just need to add the data to the request using the json parameter of the POST request:
import httpx
url = 'https://httpbin.org/post'
data = {'key': 'value'}
# Send POST request with JSON data using the json parameter
response = httpx.post(url, json=data)
# Print the response
print(response.json())
The Python HTTPX library will automatically encode the data as JSON and set the Content-Type header to application/json.
This approach can be simpler and more concise than manually encoding the data and setting the headers. Additionally, it may offer some performance benefits, as the HTTPX library can use a more efficient encoding method for JSON data.
POST Form Data Using Python HTTPX
Another common use case for using POST requests is to send form data to an endpoint.
We simply just need to add the data to the request using the data parameter of the POST request:
import httpx
url = 'https://httpbin.org/post'
data = {'key': 'value'}
# Send POST request with FORM data using the data parameter
response = httpx.post(url, data=data)
# Print the response
print(response.text)
The HTTPX library will automatically encode the data as JSON and set the Content-Type header to application/x-www-form-urlencoded so you don't have to set any headers.