HTTP Requests
The Httpx resource provides singleton HTTP clients for making HTTP requests.
It’s a shared resource that manages connection pooling and HTTP/2 support for
efficient external API calls.
Under the hood, it uses the httpx library.
Importing Httpx
Section titled “Importing Httpx”from server.resources import HttpxOverview
Section titled “Overview”Httpx provides two HTTP clients:
Httpx.sync_: Synchronoushttpx.Clientfor blocking operationsHttpx.async_: Asynchronoushttpx.AsyncClientfor async operations
Both clients are configured with HTTP/2 enabled and are managed as singletons, meaning they’re reused across requests for better performance.
Example: Complete Request Flow
Section titled “Example: Complete Request Flow”import loggingimport httpxfrom server.resources import Httpx
async def call_external_api(endpoint: str, payload: dict) -> dict: """Call external API with proper error handling.""" try: response = await Httpx.async_.post( f"https://api.example.com/{endpoint}", json=payload, headers={"Authorization": f"Bearer {API_KEY}"}, timeout=30, ) response.raise_for_status() return response.json() except httpx.HTTPStatusError as e: logging.error(f"API returned {e.response.status_code}: {e.response.text}") raise except httpx.RequestError as e: logging.error(f"Request failed: {e}") raise