Skip to content

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.

from server.resources import Httpx

Httpx provides two HTTP clients:

  • Httpx.sync_: Synchronous httpx.Client for blocking operations
  • Httpx.async_: Asynchronous httpx.AsyncClient for async operations

Both clients are configured with HTTP/2 enabled and are managed as singletons, meaning they’re reused across requests for better performance.

services/external/api.py
import logging
import httpx
from 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