Origin Academy
← Back to course

Agentic AI Engineer Phase 0 is free

Join the waitlist

Phase 0 · Module 2 of 5

Calling HTTP APIs from Python, the way production code does

HTTP and REST APIs · 11 min read

An AI agent is, mechanically, a program that calls APIs: a model provider's API to think, and other APIs to act. So before any LLM appears, you need to call HTTP APIs well: with timeouts, error handling and retries, because in production every network call eventually fails.

A request and its parts

An HTTP request has a method (GET to read, POST to create or send), a URL, headers (such as Authorization for an API key) and sometimes a JSON body. The response has a status code (2xx success, 4xx your mistake, 5xx theirs), headers and a body, usually JSON.

A careful API call

# pip install httpx
import time
import httpx

def get_repo(owner: str, name: str, retries: int = 3) -> dict:
    url = f"https://api.github.com/repos/{owner}/{name}"
    for attempt in range(retries):
        try:
            r = httpx.get(url, timeout=10.0, headers={"Accept": "application/vnd.github+json"})
        except httpx.TransportError:
            r = None                      # network problem: worth retrying
        if r is not None and r.status_code < 500 and r.status_code != 429:
            r.raise_for_status()          # 4xx: our mistake, retrying won't help
            return r.json()
        time.sleep(2 ** attempt)          # back off: 1s, 2s, 4s
    raise RuntimeError(f"gave up on {url} after {retries} attempts")

repo = get_repo("python", "cpython")
print(repo["full_name"], repo["stargazers_count"])

Three habits are packed in here. A timeout, so a slow server can't hang your program forever. Retrying only what's worth retrying: network errors, 5xx and 429 (rate limited), never 4xx. And exponential backoff, so you don't hammer a service that is already struggling.

Why this matters for agents

A single agent task can make dozens of model calls and tool calls. If each succeeds 99% of the time, a 50-step task fails about four times in ten unless every call handles failure like this. Reliable agents start with boring, careful plumbing.

Try it

  • Call get_repo with a repository that doesn't exist. What status code comes back, and why doesn't the code retry?
  • Add a random jitter to the backoff. Why do big systems do that?
  • Rewrite get_repo with httpx.AsyncClient and fetch five repositories at once with asyncio.gather.

In the full course you go on to how LLMs work, tool use and the Model Context Protocol, retrieval, agent memory and context engineering, evals and guardrails, and deploying agents you can trust in production.

Next in Phase 0

Async Python

Continue →