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()
def fetch_json(url: str) -> dict:
try:
response = httpx.get(url, timeout=10)
response.raise_for_status()
return response.json()
except httpx.TimeoutException as exc:
raise RuntimeError("The server did not respond within 10 seconds") from exc
except httpx.HTTPStatusError as exc:
raise RuntimeError(
f"HTTP {exc.response.status_code}: {exc.response.text}"
) from exc
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!