Python HTTP Data Fetching
Fetch remote data in Python using httpx with async support, retry logic, timeout handling, response parsing with Pydantic models, and connection pooling for.
Code
import httpx
from pydantic import BaseModel
class User(BaseModel):
id: int
name: str
email: str
async def fetch_user(user_id: int) -> User:
async with httpx.AsyncClient(timeout=10.0) as client:
for attempt in range(3):
try:
res = await client.get(f'https://api.example.com/users/{user_id}')
res.raise_for_status()
return User(**res.json())
except httpx.HTTPError:
if attempt == 2:
raise