snippetpythonhttpxTippending
Python httpx for modern async HTTP requests
Viewed 0 times
httpxasyncHTTP2clientstreamingrequests
Problem
requests library is synchronous only. Need async HTTP client with modern features like HTTP/2 and connection pooling.
Solution
httpx provides sync and async APIs with modern features:
import httpx
# Sync (drop-in replacement for requests):
response = httpx.get('https://api.example.com/users')
response.raise_for_status() # Raise on 4xx/5xx
data = response.json()
# Async:
async with httpx.AsyncClient() as client:
response = await client.get('https://api.example.com/users')
data = response.json()
# With connection pooling and base URL:
async with httpx.AsyncClient(
base_url='https://api.example.com',
headers={'Authorization': 'Bearer token'},
timeout=30.0,
) as client:
users = await client.get('/users')
orders = await client.get('/orders')
# HTTP/2 support:
async with httpx.AsyncClient(http2=True) as client:
response = await client.get('https://example.com')
# Streaming large responses:
async with client.stream('GET', url) as response:
async for chunk in response.aiter_bytes():
f.write(chunk)
# Retry with tenacity:
from tenacity import retry, stop_after_attempt
@retry(stop=stop_after_attempt(3))
async def fetch(url):
async with httpx.AsyncClient() as client:
r = await client.get(url)
r.raise_for_status()
return r.json()
import httpx
# Sync (drop-in replacement for requests):
response = httpx.get('https://api.example.com/users')
response.raise_for_status() # Raise on 4xx/5xx
data = response.json()
# Async:
async with httpx.AsyncClient() as client:
response = await client.get('https://api.example.com/users')
data = response.json()
# With connection pooling and base URL:
async with httpx.AsyncClient(
base_url='https://api.example.com',
headers={'Authorization': 'Bearer token'},
timeout=30.0,
) as client:
users = await client.get('/users')
orders = await client.get('/orders')
# HTTP/2 support:
async with httpx.AsyncClient(http2=True) as client:
response = await client.get('https://example.com')
# Streaming large responses:
async with client.stream('GET', url) as response:
async for chunk in response.aiter_bytes():
f.write(chunk)
# Retry with tenacity:
from tenacity import retry, stop_after_attempt
@retry(stop=stop_after_attempt(3))
async def fetch(url):
async with httpx.AsyncClient() as client:
r = await client.get(url)
r.raise_for_status()
return r.json()
Why
httpx is the modern Python HTTP client: async support, HTTP/2, connection pooling, and API compatible with requests.
Revisions (0)
No revisions yet.