HTTP APIs, Auth, Retries & Rate Limits
Customer APIs stall, rate-limit, and expire tokens in production. Build a typed HTTP client with httpx and Pydantic featuring explicit timeouts, bearer authentication, exponential backoff with jitter, and deterministic unit tests.
Forward Deployed AI Engineers rarely build systems in isolation. Every useful agent or workflow eventually calls external APIs—CRM systems, ticketing queues, internal knowledge bases, or model providers. In local demos, a quick HTTP call looks fine. In customer environments, networks stall, tokens expire, and rate limits trigger under burst traffic.
In this module, you will build a typed, resilient HTTP API client in Python using httpx, pydantic, and python-dotenv, handle numeric and HTTP-date Retry-After headers with delay caps, and verify failure modes offline with httpx.MockTransport and pytest.
What You Will Build
- Validated client configuration (
ApiClientConfig): Validate HTTP/HTTPSbase_url, non-emptyapi_token, timeouts, retry limits, and retry delay caps, and load.envviapython-dotenvinsideApiClientConfig.from_env(). - Resilient HTTP wrapper (
ResilientApiClient): Enforce explicit timeouts, sendAuthorization: Bearerheaders, fail fast on401/403/400errors, and retry transient429,5xx, and network/timeout failures onget_json(). - Bounded rate-limit handling: Parse both numeric seconds and HTTP-date
Retry-Afterheaders, fall back cleanly to exponential backoff with jitter when malformed, and clamp sleep intervals tomax_retry_delay_seconds. - Deterministic unit tests: Test
200success,401/403/400non-retryable errors, numeric/HTTP-date/malformedRetry-Aftercases, delay capping, retry exhaustion, and timeouts offline.
1. Retry Policy, Idempotency, and Retry Budget
Before writing retry logic, separate three distinct decisions so they do not get tangled together:
- Retry policy (which failures justify another attempt): Transient transport errors, timeouts,
429 Too Many Requests, and500/502/503/504server errors are worth retrying. Client and auth errors like400,401,403, and404should fail immediately. - Idempotency (whether repeating the operation is safe): An operation is idempotent if running it multiple times produces the same state as running it once. Safe read requests (
get_json()) are the focus here; mutatingPOSTrequests and idempotency keys are outside this module’s scope because blindly retrying a non-idempotent write can create duplicate records or charges. - Retry budget (how many attempts and how much total wait time you can afford): Setting
max_retries=3means up to 3 retry attempts after the initial request (4 total attempts =1 + max_retries). If all attempts fail, the client raisesRateLimitError(for exhausted429responses) orApiError(for exhausted5xx, network, or timeout errors). Excessively largeRetry-Aftervalues are clamped tomax_retry_delay_secondsso a single header cannot block a worker indefinitely.
2. Step-by-Step Build Walkthrough
- Set up the project, virtual environment, and
.env: Create yourfde-00-3workspace, activate a dedicated.venv, install dependencies (includingpython-dotenv), and copy.env.exampleto.env. Environment variables are process-level key-value settings (such as tokens and base URLs) kept outside code so you can configure environments safely.mkdir -p fde-00-3/src/fde_00_3 fde-00-3/tests cd fde-00-3 python3 -m venv .venv source .venv/bin/activate python -m pip install --upgrade pip python -m pip install -e ".[dev]" cp .env.example .env - Load
.envand validate settings viaApiClientConfig.from_env(): Pydantic’sBaseModelvalidates types and fields, whileload_dotenv(override=False)insidefrom_env()loads values from a local.envfile without overriding already-exported environment variables.class ApiClientConfig(BaseModel): model_config = ConfigDict(str_strip_whitespace=True, extra="forbid") base_url: AnyHttpUrl = Field(default="https://api.example.com/v1") api_token: str = Field(..., min_length=1) timeout_seconds: float = Field(default=10.0, gt=0.0, le=120.0) max_retries: int = Field(default=3, ge=0, le=10) base_backoff_seconds: float = Field(default=0.5, ge=0.0, le=30.0) max_retry_delay_seconds: float = Field(default=30.0, ge=0.0, le=300.0) @classmethod def from_env(cls, environ: Optional[dict[str, str]] = None) -> ApiClientConfig: if environ is None: load_dotenv(override=False) env = dict(os.environ) else: env = environ return cls( base_url=env.get("API_BASE_URL", "https://api.example.com/v1"), api_token=env.get("API_TOKEN", ""), timeout_seconds=float(env.get("API_TIMEOUT_SECONDS", 10.0)), max_retries=int(env.get("MAX_RETRIES", 3)), base_backoff_seconds=float(env.get("BASE_BACKOFF_SECONDS", 0.5)), max_retry_delay_seconds=float(env.get("MAX_RETRY_DELAY_SECONDS", 30.0)), ) - Enforce fail-fast auth checks and bounded
Retry-After+ jitter backoff: Fail immediately on401/403. For transient retries,_compute_delay()supports numeric seconds and HTTP-dateRetry-Afterheaders, falls back to exponential backoff with jitter when malformed or missing, and clamps every sleep duration tomax_retry_delay_seconds.def _compute_delay(self, attempt: int, response: Optional[httpx.Response]) -> float: if response is not None: retry_after_header = response.headers.get("Retry-After") if retry_after_header is not None: parsed_delay = _parse_retry_after_seconds(retry_after_header) if parsed_delay is not None: return min(parsed_delay, self.config.max_retry_delay_seconds) exp = self.config.base_backoff_seconds * (2 ** attempt) jitter = random.uniform(0.0, self.config.base_backoff_seconds) return min(exp + jitter, self.config.max_retry_delay_seconds) - Test offline with
httpx.MockTransport: Run the full suite to verify200success,401/403/400immediate failures, numeric and HTTP-dateRetry-Afterheaders, malformedRetry-Afterfallback to exponential backoff, delay capping, retry exhaustion after1 + max_retriesattempts, and timeouts.python -m pytest -v
3. Security & Operational Hygiene
- Push code before linking: Make sure your
fde-00-3repository is pushed and non-empty before sharing the lesson link with learners. - Keep tokens in headers, never URLs: Always send
Authorization: Bearer <token>rather than putting secrets in query strings, keep.envgitignored, and never log raw credentials. - Bound total attempts and wait times: Pair
max_retries(1 + max_retriestotal attempts) withmax_retry_delay_secondsso retries stay predictable under incidents.
Build this
Your task: Harden the HTTP client in fde-00-3 with validated configuration, immediate auth failure handling, bounded Retry-After support (both numeric seconds and HTTP-date headers), and unit tests using httpx.MockTransport.
- Validate URLs and env settings: Ensure
ApiClientConfigvalidatesbase_urlas an HTTP/HTTPS URL, caps retry sleep viamax_retry_delay_seconds, and loads values cleanly viafrom_env(). - Fail fast on auth errors: Raise
AuthErrorimmediately on HTTP401and403without retrying. - Support
Retry-Afterwith a delay cap: Parse numeric seconds and HTTP-dateRetry-Aftervalues on HTTP429, clamping delays tomax_retry_delay_seconds. - Expand
pytestcoverage: Test200success,401and400non-retryable errors,429recovery withRetry-After, delay capping, retry exhaustion (1 + max_retriesattempts),503recovery, and timeouts. - Run the test suite: Execute
python -m pytest -vand confirm all tests pass. - Commit on a feature branch: Create
feature/api-client-hardening, commit your changes, merge intomain, and push to GitHub.
Security reminder: Use dummy URLs (such as https://api.example.com/v1) and placeholder tokens (such as test-token-123) in code, tests, and .env.example. Never commit real credentials or log Authorization headers.
Test your understanding
- Why should every outbound HTTP request in an AI pipeline specify an explicit timeout instead of relying on library defaults?
- How do retry policy, idempotency, and retry budget differ when calling external APIs?
- Why do we parse both numeric seconds and HTTP-date values for
Retry-After—and why should we still cap the resulting delay withmax_retry_delay_seconds? - How does
max_retriesrelate to the total number of HTTP attempts made byResilientApiClient? - Why should Bearer tokens be sent in HTTP headers rather than URL query parameters, and why should you publish your repo before linking it?
Reveal self-review answers (attempt the questions first)
- Explicit timeouts: Without a timeout, a stalled upstream socket can block a worker or agent step indefinitely, causing queue backlogs and cascading latency.
- Retry policy vs. idempotency vs. retry budget: Retry policy decides which failures are transient and worth retrying (
429,5xx, network/timeout vs.400/401/403). Idempotency determines whether repeating a request is safe without side-effect duplication (GETvs. mutatingPOSTwith an idempotency key). Retry budget bounds total attempts (1 + max_retries) and total wait/delay time. Retry-Afterformats and delay caps: Servers may return either delay-seconds (e.g.,2) or an HTTP-date timestamp, so handling both avoids missed backoffs—while capping withmax_retry_delay_secondsprevents a misconfigured or adversarial header from stalling a worker for hours.- Total attempts formula:
max_retriesis the number of additional retries after the initial request, so the client makes up to1 + max_retriestotal attempts before raisingRateLimitErrororApiError. - Auth headers & repo readiness: Query strings leak into server access logs, proxies, and traces, whereas
Authorization: Bearerheaders stay out of URLs; likewise, pushing a working repo before publishing a lesson avoids sending learners to an empty repository.
Questions or notes on this module?