MODULE 00.3 · PUBLISHED · ~1–2h

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/HTTPS base_url, non-empty api_token, timeouts, retry limits, and retry delay caps, and load .env via python-dotenv inside ApiClientConfig.from_env().
  • Resilient HTTP wrapper (ResilientApiClient): Enforce explicit timeouts, send Authorization: Bearer headers, fail fast on 401/403/400 errors, and retry transient 429, 5xx, and network/timeout failures on get_json().
  • Bounded rate-limit handling: Parse both numeric seconds and HTTP-date Retry-After headers, fall back cleanly to exponential backoff with jitter when malformed, and clamp sleep intervals to max_retry_delay_seconds.
  • Deterministic unit tests: Test 200 success, 401/403/400 non-retryable errors, numeric/HTTP-date/malformed Retry-After cases, 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, and 500/502/503/504 server errors are worth retrying. Client and auth errors like 400, 401, 403, and 404 should 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; mutating POST requests 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=3 means up to 3 retry attempts after the initial request (4 total attempts = 1 + max_retries). If all attempts fail, the client raises RateLimitError (for exhausted 429 responses) or ApiError (for exhausted 5xx, network, or timeout errors). Excessively large Retry-After values are clamped to max_retry_delay_seconds so a single header cannot block a worker indefinitely.

2. Step-by-Step Build Walkthrough

  1. Set up the project, virtual environment, and .env: Create your fde-00-3 workspace, activate a dedicated .venv, install dependencies (including python-dotenv), and copy .env.example to .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
  2. Load .env and validate settings via ApiClientConfig.from_env(): Pydantic’s BaseModel validates types and fields, while load_dotenv(override=False) inside from_env() loads values from a local .env file 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)),
            )
  3. Enforce fail-fast auth checks and bounded Retry-After + jitter backoff: Fail immediately on 401/403. For transient retries, _compute_delay() supports numeric seconds and HTTP-date Retry-After headers, falls back to exponential backoff with jitter when malformed or missing, and clamps every sleep duration to max_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)
  4. Test offline with httpx.MockTransport: Run the full suite to verify 200 success, 401/403/400 immediate failures, numeric and HTTP-date Retry-After headers, malformed Retry-After fallback to exponential backoff, delay capping, retry exhaustion after 1 + max_retries attempts, and timeouts.
    python -m pytest -v

3. Security & Operational Hygiene

  • Push code before linking: Make sure your fde-00-3 repository 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 .env gitignored, and never log raw credentials.
  • Bound total attempts and wait times: Pair max_retries (1 + max_retries total attempts) with max_retry_delay_seconds so retries stay predictable under incidents.
Practice assignment

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.

  1. Validate URLs and env settings: Ensure ApiClientConfig validates base_url as an HTTP/HTTPS URL, caps retry sleep via max_retry_delay_seconds, and loads values cleanly via from_env().
  2. Fail fast on auth errors: Raise AuthError immediately on HTTP 401 and 403 without retrying.
  3. Support Retry-After with a delay cap: Parse numeric seconds and HTTP-date Retry-After values on HTTP 429, clamping delays to max_retry_delay_seconds.
  4. Expand pytest coverage: Test 200 success, 401 and 400 non-retryable errors, 429 recovery with Retry-After, delay capping, retry exhaustion (1 + max_retries attempts), 503 recovery, and timeouts.
  5. Run the test suite: Execute python -m pytest -v and confirm all tests pass.
  6. Commit on a feature branch: Create feature/api-client-hardening, commit your changes, merge into main, 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.

View reference repository ↗

Knowledge check

Test your understanding

  1. Why should every outbound HTTP request in an AI pipeline specify an explicit timeout instead of relying on library defaults?
  2. How do retry policy, idempotency, and retry budget differ when calling external APIs?
  3. Why do we parse both numeric seconds and HTTP-date values for Retry-After—and why should we still cap the resulting delay with max_retry_delay_seconds?
  4. How does max_retries relate to the total number of HTTP attempts made by ResilientApiClient?
  5. 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)
  1. Explicit timeouts: Without a timeout, a stalled upstream socket can block a worker or agent step indefinitely, causing queue backlogs and cascading latency.
  2. 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 (GET vs. mutating POST with an idempotency key). Retry budget bounds total attempts (1 + max_retries) and total wait/delay time.
  3. Retry-After formats 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 with max_retry_delay_seconds prevents a misconfigured or adversarial header from stalling a worker for hours.
  4. Total attempts formula: max_retries is the number of additional retries after the initial request, so the client makes up to 1 + max_retries total attempts before raising RateLimitError or ApiError.
  5. Auth headers & repo readiness: Query strings leak into server access logs, proxies, and traces, whereas Authorization: Bearer headers stay out of URLs; likewise, pushing a working repo before publishing a lesson avoids sending learners to an empty repository.
Not completed
Discussion & field notes

Questions or notes on this module?

Leave a note or question

Comments are held in a moderation queue and appear once approved. Your email will not be published.