Python HTTPX Module
HTTPX is a fully featured HTTP client for Python 3, which provides synchronous and asynchronous APIs, and support for both HTTP/1.1 and HTTP/2. It builds on the well-established usability of requests.
Installation
pip install httpx
Synchronous Usage
The API is designed to be compatible with requests.
import httpx
r = httpx.get('https://www.example.org/')
print(r.status_code)
print(r.text)
Asynchronous Usage
To make asynchronous requests, use httpx.AsyncClient.
import httpx
import asyncio
async def main():
async with httpx.AsyncClient() as client:
r = await client.get('https://www.example.org/')
print(r.status_code)
print(r.text)
if __name__ == '__main__':
asyncio.run(main())
HTTP/2 Support
HTTPX supports HTTP/2, which can be enabled on the client.
client = httpx.Client(http2=True)
r = client.get('https://www.google.com/')
print(r.http_version) # 'HTTP/2'
Streaming Responses
For large downloads, you can stream the response.
with httpx.stream("GET", "https://www.example.com") as r:
for data in r.iter_bytes():
print(data)
Timeouts
HTTPX defaults to a 5-second timeout for all network operations. You can configure this.
# Set a 10 second timeout
httpx.get('https://github.com/', timeout=10.0)
# Disable timeouts
httpx.get('https://github.com/', timeout=None)
Calling Python Web Apps
You can use HTTPX to call a WSGI (Flask/Django) or ASGI (FastAPI) application directly, which is great for testing.
from fastapi import FastAPI
import httpx
app = FastAPI()
@app.get("/")
def read_root():
return {"Hello": "World"}
client = httpx.Client(app=app)
response = client.get("/")
print(response.json())