Python has several popular libraries for making HTTP requests like requests and urllib. A relatively newer option is HTTPX. In this article, we'll learn how to use HTTPX to make HTTP requests in Python.
What is HTTPX?
HTTPX is a next generation HTTP client for Python, built for making API requests simple and reliable. Some key features of HTTPX include:
Installation
Install HTTPX with pip:
pip install httpx
Making a GET Request
Here is a simple example to make a GET request and print the response body:
import httpx
with httpx.Client() as client:
r = client.get("https://api.example.com/users")
print(r.text)
The client handles opening and closing connections automatically.
POST Requests
Making a POST request is just as simple. Pass the data to
data = {"name": "John Doe", "email": "[email protected]"}
with httpx.Client() as client:
r = client.post("https://api.example.com/users", json=data)
Handling Responses
HTTPX responses contain properties like
r = client.get("https://api.example.com/status")
print(r.status_code) # 200
print(r.headers["Content-Type"]) # "application/json"
print(r.text) # Print response body
Check responses for errors:
if r.status_code == 200:
print("Success!")
else:
print("Request failed with status", r.status_code)
Timeouts, Retries and More
Some other useful configuration options include:
client = httpx.Client(
timeout=5.0, # Timeout per request
retries=2, # Automatic retries
verify=False, # Disable SSL verification
)
There are many more options for customizing the client and handling advanced use cases.
Conclusion
HTTPX makes sending HTTP requests in Python very simple, while providing useful functionality like connection pooling, support for HTTP standards, and configurable retries. Key takeaways:
Check out the HTTPX documentation to learn more!