httpx
A Requests-compatible HTTP client that also speaks async and HTTP/2.
What it is
httpx is a fully featured HTTP client for Python 3, supporting both synchronous and asynchronous requests, connection pooling, and HTTP/2.
httpx allows sending HTTP requests synchronously or asynchronously. It supports custom headers, cookies, timeout handling, streaming responses, and HTTP/2 features.
- Maturity
- Production-ready and widely adopted
- Licence
- BSD 3-clause
When to use it
The question documentation cannot answer for you — because it cannot recommend something else.
Reach for it when
- New Python projects — it does everything Requests does, plus async
- FastAPI or other asyncio applications that need to call out to other services
- You want to test an ASGI app in-process without starting a real server
Look elsewhere when
- You need the absolute smallest dependency footprint and only make simple synchronous calls
Installation
pip install httpxGetting started
The smallest useful thing you can do with it, and what each part means.
import httpx
response = httpx.get('https://httpbin.org/get')
print(response.status_code)
print(response.json())import httpx
import asyncio
async def fetch():
async with httpx.AsyncClient() as client:
r = await client.get('https://httpbin.org/get')
print(r.json())
asyncio.run(fetch())Advanced usage
Where the library earns its place over a simpler alternative.
import httpx
headers = {'User-Agent': 'my-app/0.0.1'}
cookies = {'session_id': '12345'}
response = httpx.get('https://httpbin.org/headers', headers=headers, cookies=cookies)
print(response.json())import httpx
try:
response = httpx.get('https://httpbin.org/delay/10', timeout=5)
except httpx.TimeoutException:
print('Request timed out')import httpx
with httpx.stream('GET', 'https://httpbin.org/stream/20') as response:
for chunk in response.iter_bytes():
print(chunk)Errors and fixes
The failures you are most likely to hit, and what actually resolves them.
- httpx.RequestError
- Catch network exceptions, invalid URLs, or connection issues.
- httpx.TimeoutException
- Set a reasonable timeout and handle it appropriately in your code.
Best practices
- Use `AsyncClient` for concurrent requests to improve performance.
- Reuse client instances to take advantage of connection pooling.
- Always set timeouts to avoid hanging requests.
- Handle exceptions such as `httpx.RequestError` for robust error management.
- Leverage HTTP/2 support for faster multiplexed requests when possible.
Alternatives
Comparable options, and the reason you would pick one over the other.
Background
Why it exists, and what it was reacting to.
httpx was created by Encode to provide a modern, high-performance HTTP client for Python. It is designed as a next-generation replacement for `requests` with async support and better HTTP/2 handling, making it ideal for modern web applications and APIs.
