SproutStackSproutStack home

APIs, JSON and Pydantic

8 min readBeginner-friendlyFree to read

Read a little, play a little. No scary maths, and no rush.

Share:

The universal conversation

Nearly everything in AI engineering is the same loop: your app POSTs JSON somewhere, JSON comes back, you validate it, you act. LLM APIs, vector DBs, tool endpoints — all speak HTTP + JSON. Master this loop once and every integration after is dialect, not discovery.

The loop, concretely

import requests
from pydantic import BaseModel

class Ticket(BaseModel):
    title: str
    priority: str  # low|high

r = requests.post(
    "https://api.example.com/chat",
    json={"messages": [{"role": "user", "content": "hi"}]},
    headers={"Authorization": "Bearer $KEY"},
    timeout=30,
)
data = Ticket.model_validate(r.json())  # throws if the shape is wrong

Three habits embedded here: timeout (never wait forever), auth header (keys travel in headers, never URLs), and validate the response — because APIs, especially LLM ones, return surprising shapes at the worst moments.

Why Pydantic earns its place

LLMs output almost-JSON: trailing commas, wrong enums, mystery fields. A Pydantic model turns that mess into a verdict — valid object or loud error — before it touches your database. Combined with the retry-with-error-message pattern from Structured Output, it closes the reliability loop.

Status codes worth memorizing

  • 401: bad/missing key — fix credentials, don't retry.
  • 429: rate-limited — back off and retry (this one is expected at scale).
  • 5xx: their problem — retry with backoff, then degrade gracefully.

Log every status; dashboards of code-counts catch outages before users report them.

Retrying politely

A retry that fires instantly, forever, turns a brief outage into a flood. Good retries follow three rules:

  • Back off exponentially. Wait 1 second, then 2, then 4, then 8, and add a little randomness (jitter) so a thousand clients do not all retry at the same instant.
  • Respect Retry-After. Many APIs send this header with a 429, telling you exactly how long to wait. Use it when it is present.
  • Give up eventually. After a few attempts, stop and report a clear error rather than hanging.
import random, time

def post_with_retry(url, payload, attempts=4):
    for i in range(attempts):
        r = requests.post(url, json=payload, timeout=30)
        if r.status_code not in (429, 500, 502, 503):
            return r
        time.sleep(2 ** i + random.random())
    r.raise_for_status()

One caution: retrying a request that creates something, such as "charge this card", can create it twice if the first attempt actually succeeded. APIs that matter offer an idempotency key for exactly this case.

Reading a new API's documentation

Before writing any code against an unfamiliar API, find five things:

  1. Authentication: which header, and where the key comes from.
  2. Rate limits: requests per minute, and what happens when you exceed them.
  3. Request and response shapes: ideally an example of each.
  4. Error format: how failures are described, so you can log them usefully.
  5. Pagination: how to fetch the next page when results are long.

Ten minutes on these saves an afternoon of guessing.

Logging what matters

When an API call misbehaves in production, your logs are the only witness. For every outbound call, record the endpoint, the status code, how long it took, and any request ID the provider returns, since support teams ask for it first. Just as important is what never to log: API keys, passwords, and full user messages that may contain personal details. A log line like POST /chat 429 in 1.8s req=abc123 is enough to diagnose most problems and safe to keep.

Remember this

  • POST JSON, validate the reply, timeout everything, keys in headers.
  • 401 = your fault, 429/5xx = retry politely. Pydantic turns hope into guarantees.

Check your understanding

5 questions · first-try answers earn the most XP

1. You get HTTP 401 from an API call. What is the right response?
2. You get HTTP 429. What does it tell you and what should you do?
3. Why validate an API response with a schema before using it?
4. Why should every outbound HTTP call from your app set a timeout?
5. Where should an API key travel in an outbound request, and where should it never go?

My notes

Saved in this browser. Highlight a line above and save it, or write it in your own words.

Nothing saved yet. Your highlights will live here.

References

Finished reading?

Ticking it here also ticks the chapter in the sidebar, the section count and your streak — it is all one number.

Related chapters

Spotted a mistake or want a topic covered? Report an issue

📬 An occasional email when new lessons land

New lessons and showdowns, no more than a few times a month. No spam, unsubscribe anytime. We store your email only to send the newsletter.