httpx is a next-generation HTTP client. Its interface is similar to requests, but it supports async/await out of the box.
Installation
uv add httpx
Basic Requests
import httpx
# GET request
response = httpx.get("https://wttr.in/Moscow?format=j1", timeout=10)
response.raise_for_status() # raises an exception on 4xx/5xx
data = response.json()
# GET with query parameters
response = httpx.get(
"https://api.example.com/search",
params={"q": "python", "limit": 10},
timeout=10
)
# POST with JSON
response = httpx.post(
"https://api.example.com/data",
json={"key": "value"},
headers={"Authorization": "Bearer token"},
timeout=10
)
timeout — Always Set It
# Without a timeout, a request can hang forever
response = httpx.get(url, timeout=10) # 10 seconds
response = httpx.get(url, timeout=None) # no limit (bad practice)
# Separate timeouts for connect and read
timeout = httpx.Timeout(connect=5.0, read=30.0)
response = httpx.get(url, timeout=timeout)
raise_for_status()
try:
response = httpx.get(url, timeout=10)
response.raise_for_status()
data = response.json()
except httpx.TimeoutException:
return "Error: server did not respond within 10 seconds"
except httpx.HTTPStatusError as e:
return f"Error {e.response.status_code}: {e.response.text}"
Reusing the Client
# Better to create a client once for multiple requests
with httpx.Client(timeout=10, base_url="https://api.example.com") as client:
r1 = client.get("/users")
r2 = client.get("/posts")
Async Client
import asyncio
import httpx
async def fetch(url: str) -> dict:
async with httpx.AsyncClient(timeout=10) as client:
response = await client.get(url)
response.raise_for_status()
return response.json()
# Parallel requests
async def fetch_all(urls: list[str]) -> list[dict]:
async with httpx.AsyncClient(timeout=10) as client:
tasks = [client.get(url) for url in urls]
responses = await asyncio.gather(*tasks)
return [r.json() for r in responses]
httpx vs requests
| requests | httpx | |
|---|---|---|
| Sync | ✅ | ✅ |
| Async | ❌ | ✅ |
| HTTP/2 | ❌ | ✅ |
| Type hints | partial | full |
| API | identical | identical |
💬 Comments (0)
No comments yet
Be the first to share your opinion about this article!