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.

PythonData Fetching

Code

snippet
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

How it works

All of the logic lives in the class User and the function fetch_user.

Repetition is confined to for attempt in range(3) — the rest of the file is straight-line. Asynchronous boundaries use await, so failures surface as exceptions at the call site rather than being swallowed. From pydantic it pulls BaseModel — the imports name exactly which library surface the snippet touches.

What to watch for

  • Dependency check: pydantic and httpx — not built-in, must be present in the project.
  • The guard attempt == 2 short-circuits the flow with an early raise when its condition holds.

Putting it to use

The main signature reads def fetch_user(user_id: int) -> User

fetch_user is what another module would consume; nothing else here is load-bearing for callers.

Core lines

except httpx.HTTPError:
    if attempt == 2:
        raise

Interactive Tools for This Topic

FAQ

What does this need from the package registry?
These are real dependencies: `pydantic` and `httpx`. Without them the snippet will not load.