snippetpythonModeratepending
Python httpx -- modern async HTTP client
Viewed 0 times
httpxasyncHTTP clientstreamingconnection pooltimeout
python
Problem
requests library is synchronous only. aiohttp has a complex API. Need a modern HTTP client that supports both sync and async with a clean interface.
Solution
httpx provides requests-compatible API with async support, HTTP/2, streaming, and connection pooling.
Code Snippets
httpx sync and async patterns
import httpx
# Sync (like requests)
resp = httpx.get('https://api.example.com/users')
users = resp.json()
# Async with connection pooling
async with httpx.AsyncClient(
base_url='https://api.example.com',
headers={'Authorization': f'Bearer {token}'},
timeout=30.0,
) as client:
users = (await client.get('/users')).json()
# Connection is reused
posts = (await client.get('/posts')).json()
# Streaming large responses
async with client.stream('GET', '/large-file') as resp:
async for chunk in resp.aiter_bytes(chunk_size=8192):
f.write(chunk)
# Retry with tenacity
from tenacity import retry, stop_after_attempt
@retry(stop=stop_after_attempt(3))
async def fetch_with_retry(url):
resp = await client.get(url)
resp.raise_for_status()
return resp.json()Revisions (0)
No revisions yet.