Guide Home Part 1 - FastAPI Foundations Part 2 - Building Applications Part 3 - Pages and HTML Part 4 - Security and Deployment Part 5 - Going Further Capstone Build Plan Markdown Source All Guides

Chapter 33: Calling Remote APIs

ASP.NET Core uses HttpClientFactory to manage clients and avoid socket exhaustion. Python commonly uses HTTPX.

import httpx


class NutritionClient:
    def __init__(self, client: httpx.AsyncClient, base_url: str):
        self._client = client
        self._base_url = base_url

    async def estimate_calories(self, ingredients: list[str]) -> int:
        response = await self._client.post(
            f"{self._base_url}/estimate",
            json={"ingredients": ingredients},
        )
        response.raise_for_status()
        data = response.json()
        return int(data["calories"])

Practices:

Register shared HTTP clients in lifespan or app state, then inject wrapper clients through dependencies.