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:
- Reuse clients. Do not create a new client per request.
- Set timeouts.
- Handle retries only for safe operations or explicitly idempotent commands.
- Use circuit breakers or backoff for fragile dependencies.
- Log remote failures with correlation IDs.
- Hide vendor payloads behind your own client interface.
Register shared HTTP clients in lifespan or app state, then inject wrapper clients through dependencies.