Originally published on my newsletter, The Path to AI FDE. Subscribe free to get each issue by email.

This is a “From Zero” issue. So far, every API we’ve called has been open to anyone. Real AI APIs aren’t: they need to know who you are (so they can bill you) and they cap how much you can ask for (so one user can’t swamp everyone else). Today covers both.

You need the same setup as yesterday (#24): your api-practice uv project with httpx added (run scripts with uv run). Everything here is safe to run. We use httpbin’s practice login check, a fake API that runs entirely on your computer, and made-up tokens. No real key appears anywhere, and you shouldn’t paste one in either.

Cover card titled "API keys, auth and rate limits, from Zero" for issue 25 of The Path to AI FDE by Dhanush Kumar Sivaji. Subtitle: how an API knows who you are and how much you're allowed. Six numbered cards in two lanes. Part A, who you are: 1, authentication, proving who you are with a key, with a chip saying no key gets 401; 2, the header, shown as Authorization: Bearer <key>, though some providers use their own header name; 3, keys stay on the server, where your backend holds the key, with a warning: never in browser or app code. Part B, how much you're allowed: 4, rate limits, requests or tokens per minute, with a chip saying too many gets 429; 5, Retry-After, shown as Retry-After: 2, where the server says how long to wait; 6, quotas and billing, where usage costs money, with a warning to set a spending limit first. A tip bar says the key is your ticket, and the rate limit is the turnstile.

Part A · Who you are

Diagram titled "Authentication: who are you?", subtitle: the same request, without and with a key. Left panel, no key: GET /bearer with Host: httpbin.org gets 401 Unauthorized, plus WWW-Authenticate: Bearer, meaning send me a bearer token. Right panel, with a made-up key: the same request plus the highlighted header Authorization: Bearer demo-token-123 gets 200 and {'authenticated': True, 'token': 'demo-token-123'}. Below, a code panel says the key comes from an environment variable, not the code: token = os.environ("DEMO_TOKEN"), then r = httpx.get(url, headers={"Authorization": f"Bearer {token}"}, timeout=10), then print("With key:", r.status_code, r.json()); the output is With key: 200 and the same dictionary. A note says to set it first in the terminal with export DEMO_TOKEN="demo-token-123", a made-up value. A tip bar says a key is a ticket: whoever holds it gets in, so guard it like a password.

1. Authentication: proving who you are. An API key (or token) is a long random string the provider gives you. You send it with every request, and the server checks it. httpbin has a practice endpoint, /bearer, that accepts any token, so you can see both sides safely.

First, put a made-up token in an environment variable, a named value your terminal hands to programs (#13). On macOS or Linux:

export DEMO_TOKEN="demo-token-123" 

(On Windows PowerShell: $env:DEMO_TOKEN = "demo-token-123".) Then, in the same terminal:

import os import httpx url = "https://httpbin.org/bearer" r = httpx.get(url, timeout=10) print("No key:", r.status_code, r.headers.get("www-authenticate")) token = os.environ["DEMO_TOKEN"] r = httpx.get(url, headers={"Authorization": f"Bearer {token}"}, timeout=10) print("With key:", r.status_code, r.json()) 
No key: 401 Bearer With key: 200 {'authenticated': True, 'token': 'demo-token-123'} 

No key gets 401 Unauthorized, plus a WWW-Authenticate header naming the kind of credential it expects. With a key, you get 200. The standard calls this a bearer token for a reason: anyone who holds it can use it. Treat a real key like a password.

Diagram titled "Where the key goes", subtitle: two common header styles, and two errors to tell apart. Left card, the standard style: Authorization: Bearer <key>, the word Bearer, a space, then the key, used by many APIs. Right card, a provider's own header: x-api-key: <key>, an example, since some providers pick their own name. A bar says it's the same kind of secret with a different label, so copy the header name from your provider's docs. Two error cards: 401 Unauthorized, the key is missing, mistyped or revoked, so check the key; 403 Forbidden, the server knows who you are, but this key isn't allowed to do this. A card titled "Headers, never the URL" contrasts a header, ticked, with https://api.example.com/v1/data?key=..., crossed out, because URLs end up in logs and history. A tip bar says 401 means who are you, and 403 means I know you, and no.

2. The Authorization header, and its cousins. The key travels in a header. There are two common styles:

  • Standard · Authorization: Bearer <key> · The word Bearer, a space, then the key. Many APIs use this.
  • Provider-specific · for example x-api-key: <key> · Some providers pick their own header name.

Both carry the same kind of secret; only the label differs. Your provider’s docs tell you which one to use, so copy the header name from there. Two status codes to tell apart:

  • 401 Unauthorized: the key is missing, mistyped or revoked. Check the key.
  • 403 Forbidden: the server knows who you are, but your key isn’t allowed to do this, for example a model your account can’t use.

And as #23 warned: keys go in headers, never in the URL, because URLs end up in logs.

Diagram titled "Keys stay on the server", subtitle: the browser talks to you, and you talk to the provider. A green panel, the safe shape, shows three boxes joined by arrows: browser or app, with no provider key; your server, which reads the key from an environment variable; AI provider, which checks the key. An orange warning panel: key in browser JavaScript or a mobile app, where anyone can open developer tools, or unpack the app, and copy it, then spend your money. A code panel titled "On your server: read it, check it, never print it whole": key = os.environ.get("DEMO_API_KEY"); if not key, raise SystemExit("Set DEMO_API_KEY first. Never paste a key into your code."); otherwise print("Key loaded, ending in", key(-4:)). The output is Key loaded, ending in 7f3a, run with the made-up value demo-key-not-real-7f3a, and a note says to list any .env file in .gitignore. A tip bar says the provider key lives only on a server you control.

3. Keys stay on the server. Anything you ship to a browser or a phone app can be read by whoever uses it: open the browser’s developer tools, or unpack the app, and the key is right there. So the rule is simple: the provider key lives only on a server you control. The browser talks to your server, and your server talks to the provider.

On that server, read the key from the environment, never from your code:

import os key = os.environ.get("DEMO_API_KEY") if not key: raise SystemExit("Set DEMO_API_KEY first. Never paste a key into your code.") print("Key loaded, ending in", key[-4:]) 

With nothing set, it stops with the message Set DEMO_API_KEY first. Never paste a key into your code. With a made-up value such as demo-key-not-real-7f3a, it prints:

Key loaded, ending in 7f3a 

Printing just the last four characters lets you check which key loaded without exposing it. If you keep keys in a .env file for convenience, add .env to your .gitignore (#11) so it never reaches GitHub.

Part B · How much you’re allowed

Diagram titled "Rate limits: the turnstile", subtitle: your key is the ticket, and the counter decides when you wait. A code panel shows a fake fortune-cookie API that runs offline and allows 3: a function toy_api counts calls and, after 3, returns httpx.Response(429, headers={"Retry-After": "2"}); otherwise it returns 200 with a fortune, "Good news is on its way." A client is built with transport=httpx.MockTransport(toy_api) and base_url="https://fortune.example". Below, five quick requests as tiles: requests 1, 2 and 3 return 200 in green; requests 4 and 5 return 429 in orange, each with Retry-After: 2. Three cards: per minute, requests per minute and for AI APIs often tokens per minute; per day, some limits run over longer windows; by tier, limits often grow with your account tier. A tip bar says going over any limit gets 429 Too Many Requests.

4. Rate limits: how much, how fast. Providers cap how much each key can do: requests per minute, and for AI APIs often tokens per minute (tokens are chunks of text, a later issue) or per day. The limits usually depend on your account tier. Go over any of them and you get 429 Too Many Requests.

To see one without hammering a real service, here’s a fake fortune-cookie API that runs entirely on your computer. httpx’s MockTransport sends requests to a Python function instead of the internet. This one allows three requests:

import httpx calls = 0 def toy_api(request): global calls calls += 1 if calls > 3: return httpx.Response(429, headers={"Retry-After": "2"}) return httpx.Response(200, json={"fortune": "Good news is on its way."}) client = httpx.Client( transport=httpx.MockTransport(toy_api), base_url="https://fortune.example", ) for i in range(1, 6): r = client.get("/fortune") print(i, r.status_code, r.headers.get("Retry-After")) 
1 200 None 2 200 None 3 200 None 4 429 2 5 429 2 

Requests four and five are turned away. (fortune.example is a reserved example name, and nothing leaves your machine.) Real limits reset over time, such as each minute, while this toy just counts.

Diagram titled "Retry-After: wait, then retry", subtitle: when the server says how long, listen. A code panel titled "Read the header, sleep, try again, and stop after a few tries" shows get_with_retry(path, max_tries=4): for each attempt it gets the path and returns the response unless the status is 429; otherwise it reads Retry-After (default 5), prints the attempt and wait, and sleeps; after max_tries it raises RuntimeError("Still rate limited, giving up"). The output is Try 1: 429, waiting 1 s; Try 2: 429, waiting 1 s; 200 Patience pays. A note says the toy API answers the first two tries with 429 and Retry-After: 1, then 200. Two contrast cards: polite client, 429, wait 1 s, 429, wait 1 s, 200, capped at 4 tries; tight loop, 429 again and again, instantly, forever, earning more 429s. Two notes: Retry-After can be a number of seconds or an HTTP date, and this toy handles only seconds; with no header, wait a little longer after each failure, called backoff, with a full lesson later. A tip bar says retry 429 and some 5xx, and never retry a 401.

5. Retry-After: the server tells you when. A 429 (or a 503) may come with a Retry-After header: how long to wait before trying again. The polite client reads it, sleeps, then retries, and gives up after a few tries:

import time import httpx calls = 0 def toy_api(request): global calls calls += 1 if calls <= 2: return httpx.Response(429, headers={"Retry-After": "1"}) return httpx.Response(200, json={"fortune": "Patience pays."}) client = httpx.Client( transport=httpx.MockTransport(toy_api), base_url="https://fortune.example", ) def get_with_retry(path, max_tries=4): for attempt in range(1, max_tries + 1): r = client.get(path) if r.status_code != 429: return r wait = int(r.headers.get("Retry-After", "5")) print(f"Try {attempt}: 429, waiting {wait} s") time.sleep(wait) raise RuntimeError("Still rate limited, giving up") r = get_with_retry("/fortune") print(r.status_code, r.json()["fortune"]) 
Try 1: 429, waiting 1 s Try 2: 429, waiting 1 s 200 Patience pays. 

Two honest caveats. Retry-After can also be a date rather than a number of seconds; this toy handles only seconds. And when there’s no header, the usual move is to wait a little longer after each failure (”backoff”). Proper retries get a full issue later in the series.

Diagram titled "Quotas and billing", subtitle: usage costs money, so cap it before you loop. An orange panel labelled "Illustrative numbers only (not any provider's price)" shows the sum $0.002 per call, times 600 calls per minute from a buggy loop, times 60 minutes, equals $72.00 per hour, and $1,728.00 per day if nobody notices. A green checklist titled "Before your first loop over a paid API": set a spending limit or budget alert in the provider's console, where offered; use a separate key per project, so you can see and revoke each one; test on small inputs first; check the usage page after your first runs. Two cards: rate limits protect the provider; spending limits protect you. A tip bar says a fraction of a cent per call becomes a real bill overnight.

6. Quotas and billing: usage costs money. Every successful call to a paid API is billed, usually by how much text goes in and out. Small amounts add up fast when code goes wrong. Here’s illustrative arithmetic (the price is made up, not any provider’s):

price_per_call = 0.002 # illustrative price in US dollars, not a real one calls_per_minute = 600 # a loop with a bug in it per_hour = price_per_call * calls_per_minute * 60 print(f"${per_hour:,.2f} per hour") print(f"${per_hour * 24:,.2f} per day") 
$72.00 per hour $1,728.00 per day 

A fraction of a cent per call turns into a real bill overnight. Before you write your first loop over a paid API:

  • Set a spending limit or budget alert in the provider’s console, where the provider offers one.
  • Use a separate key per project, so you can see who spent what and revoke one without breaking the others.
  • Test on small inputs first, and check the usage page after your first runs.

Rate limits protect the provider. Spending limits protect you.

Try it (20 minutes)

  1. Run the /bearer snippet from point 1. Then change the environment variable to a different made-up value and run it again: httpbin echoes back whatever token you sent.
  2. Run the rate-limit toy from point 4 with calls > 1 instead of calls > 3. How many 200s do you get now?
  3. The main exercise: pick one AI provider you’re curious about and find its rate limits page in the official docs. Don’t sign up and don’t create a key; reading is enough. Fill in this table:
  • Which limit types? (requests/min, tokens/min, per day...)
  • Do limits change with account tier or spend?
  • Which response headers report your remaining limit?
  • What status code do you get when you go over?
  • Do they send Retry-After?
  • Where do you set a spending limit or alert?
  • Which header carries the key? (Authorization: Bearer or their own)

Keep the table: you’ll want it next week.

Check your understanding: your script gets 401 on one call and 429 on another. What does each mean, and should you retry either one?

Answer: 401 means the key is missing or wrong. Retrying won’t help, so fix the key. 429 means you’re over a rate limit. Wait (for Retry-After if it’s sent), then retry a limited number of times.

Common beginner mistakes

  • Putting a key in front-end code. Browser JavaScript and mobile apps can be read by anyone who has them. Keep keys on your server (point 3).
  • Retrying in a tight loop. Hitting the API again the instant you get a 429 just earns more 429s and can get your key throttled further. Wait, and cap the number of tries.
  • Pasting a key into code and committing it. Even in a private repo, it ends up in history. Use environment variables, and add .env to .gitignore. If a key ever leaks, revoke it in the console and make a new one. Deleting the file isn’t enough.
  • Printing the whole key in logs. Logs get shared. Print the last four characters at most.
  • Retrying a 401. A wrong key stays wrong. Only 429 and some 5xx are worth waiting out.

Takeaway

An API key proves who you are; send it in a header (Authorization: Bearer ... or the provider’s own name) and keep it on your server. 401 means fix the key. 429 means slow down: wait for Retry-After, retry a few times, then stop. Usage costs money, so set a spending limit before your first loop.

Where this fits in my roadmap: this finishes the “how APIs work” basics. Next week: your first LLM API call, where everything from #23 to #25 comes together. Later in the series, timeouts, rate limits and safe retries get a full lesson of their own.

Over to you: which provider’s rate-limit page did you read for the Try it, and what surprised you? Reply with one line.

Sources

  1. IETF, RFC 6750 “The OAuth 2.0 Authorization Framework: Bearer Token Usage”: a bearer token is one where “any party in possession of the token (a “bearer”) can use the token in any way that any other party in possession of it can”, and the example header Authorization: Bearer mF_9.B5f-4.1JqM. https://www.rfc-editor.org/rfc/rfc6750.html
  2. IETF, RFC 9110 “HTTP Semantics”: 401 “lacks valid authentication credentials for the target resource” (15.5.2); Authorization (11.6.2); Retry-After “can be either an HTTP-date or a number of seconds to delay after receiving the response” (10.2.3). https://www.rfc-editor.org/rfc/rfc9110.html
  3. IETF, RFC 6585, section 4 (429 Too Many Requests): responses “MAY include a Retry-After header indicating how long to wait before making a new request.” https://www.rfc-editor.org/rfc/rfc6585.html#section-4
  4. MDN, “Authorization header”. https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Authorization
  5. MDN, “401 Unauthorized”. https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status/401
  6. MDN, “429 Too Many Requests”. https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status/429
  7. MDN, “Retry-After header”. https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Retry-After
  8. HTTPX, Transports: “The httpx.MockTransport class accepts a handler function, which can be used to map requests onto pre-determined responses”. https://www.python-httpx.org/advanced/transports/
  9. Python docs, os module (os.environ). https://docs.python.org/3/library/os.html
  10. OWASP, Secrets Management Cheat Sheet (keeping secrets out of code, rotation and revocation). https://cheatsheetseries.owasp.org/cheatsheets/Secrets_Management_Cheat_Sheet.html
  11. httpbin, “A simple HTTP Request & Response Service” (/bearer). https://httpbin.org/

All code ran on Nov 2, 2026 with Python 3.13 and httpx 0.28.1. The /bearer call used a made-up token; the rate-limit and retry examples use an offline fake API; prices are illustrative, not any provider’s. No real API keys were used. Sources checked Nov 2, 2026.

Free: the 5-page roadmap from Novice to AI FDE.

If this was useful, subscribe to The Path to AI FDE for the next issue.