Chapter 3 · HTTP and Web APIs
Reliable API Calls: Timeouts, Retries, Pagination and LLM APIs
- Page 15 of 22
- 22 min read
A call that works on your laptop on a quiet afternoon is not yet a reliable call. In production, networks drop packets, servers restart, providers rate-limit you, and an LLM provider has a bad five minutes every few weeks. A script that crashes on the first 503 will lose a night's work; a script that retries blindly can hammer a struggling server or charge you twice. Reliability is a small amount of careful code: retry what is worth retrying, wait the right amount, reuse connections, save what you fetched, and put all of it in one place.
This page builds that in steps with the Practice API: retries with backoff for 429 and 503, honouring Retry-After, requests.Session, saving results to JSON and CSV, a reusable client class, and finally a call to an LLM-style chat API with token and cost tracking. It continues directly from Calling APIs from Python with requests.
What you will learn
- Which failures are worth retrying and which are not, and how exponential backoff, jitter and
Retry-Afterwork. - Write a retry function, and see the built-in alternative (
urllib3'sRetrywith aSession). - Use
requests.Sessionfor shared headers and connection reuse. - Save API results to JSON and CSV files safely.
- Package everything into a reusable client class, then use it to call a chat API (non-streaming) and track tokens and cost.
Setting up
Keep the Practice API running in its second terminal. In your first terminal, make a project and put the two settings the code will read into environment variables, as you learned on the previous page:
mkdir -p ~/projects/reliable-client
cd ~/projects/reliable-client
python -m venv .venv
source .venv/bin/activate
pip install -q requests
export PRACTICE_BASE_URL="http://localhost:8800"
export PRACTICE_TOKEN="token-nadia-001"(With uv: uv init and uv add requests. The token is the one POST /v1/token gave you in Web APIs and REST: Reading Docs and Testing with curl; a real provider would hand you a key from its dashboard. PowerShell: $env:PRACTICE_TOKEN = "token-nadia-001".)
Transient failures and what to retry
Some failures are transient: asking again a moment later will probably work. Others are permanent: asking again just fails again, and wastes time or money. The Practice API's /v1/flaky endpoint fails with 503 for the first fail_times calls that share a key, then succeeds. A naive loop shows the idea:
import json
import os
import random
import time
import requests
BASE = os.environ["PRACTICE_BASE_URL"]
TIMEOUT = (3.05, 10)
for attempt in range(1, 5):
r = requests.get(f"{BASE}/v1/flaky", params={"key": "demo-1", "fail_times": 2}, timeout=TIMEOUT)
print(attempt, r.status_code, r.json())
if r.ok:
break1 503 {'detail': 'Service temporarily unavailable'}
2 503 {'detail': 'Service temporarily unavailable'}
3 200 {'ok': True, 'attempt': 3}Which failures to retry:
| Outcome | Retry? | Why |
|---|---|---|
| Connection error, timeout | Yes (with care) | Network blip, server restarting |
429 Too Many Requests | Yes, after waiting | You are over the limit; the limit resets |
500, 502, 503, 504 | Yes | Server or gateway trouble, often short-lived |
400, 404, 422 | No | Your request is wrong; it will be wrong again |
401, 403 | No | Bad or missing credentials, fix them |
One more caution: retrying a request that changes something (a POST that creates an order) can do it twice if the first attempt actually succeeded but the answer was lost. Retry GET, PUT and DELETE freely; retry POST only when a duplicate is harmless (a chat completion only costs money) or the API supports an idempotency key (you meet those in the advanced tutorial).
Exponential backoff
Retrying immediately in a tight loop makes an overloaded server worse. Exponential backoff waits longer after each failure: 0.1 s, 0.2 s, 0.4 s, 0.8 s … doubling, up to a cap. Real services use bigger numbers (1 s, 2 s, 4 s …); we use small ones so the page runs quickly.
def backoff_delay(attempt, base=0.1, cap=5.0):
"""Seconds to wait after the given failed attempt (1, 2, 3 ...)."""
return min(cap, base * 2 ** (attempt - 1))
print([backoff_delay(n) for n in range(1, 8)])[0.1, 0.2, 0.4, 0.8, 1.6, 3.2, 5.0]Add jitter: a little randomness. If a thousand clients all failed at the same moment, plain backoff makes them all retry at the same moment again. Waiting a random time between 0 and the computed delay ("full jitter") spreads them out. And if the server tells you exactly how long to wait, listen: a 429 usually carries a Retry-After header with a number of seconds (it can also be a date; we handle the number form). Here is the whole idea as one function:
RETRY_STATUSES = {429, 500, 502, 503, 504}
def request_with_retries(method, url, *, session=None, max_attempts=4, base=0.1, cap=5.0,
jitter=True, on_retry=None, **kwargs):
"""Send a request, retrying transient failures. Returns the last response."""
caller = session or requests
kwargs.setdefault("timeout", TIMEOUT)
for attempt in range(1, max_attempts + 1):
last = attempt == max_attempts
retry_after = None
try:
response = caller.request(method, url, **kwargs)
except (requests.exceptions.ConnectionError, requests.exceptions.Timeout) as error:
if last:
raise
reason = type(error).__name__
else:
if response.status_code not in RETRY_STATUSES or last:
return response
reason = str(response.status_code)
header = response.headers.get("Retry-After", "")
retry_after = int(header) if header.isdigit() else None
delay = backoff_delay(attempt, base, cap)
if jitter:
delay = random.uniform(0, delay)
if retry_after is not None:
delay = max(delay, min(retry_after, 30)) # obey the server, but not forever
if on_retry:
on_retry(attempt, reason, delay)
time.sleep(delay)Read it slowly; every line is a decision. The loop gives up after max_attempts (never retry forever). Network exceptions are retried, and re-raised on the last attempt. A response with a status that is not in RETRY_STATUSES is returned at once, so 404 and 422 come straight back to the caller. On the last attempt the response is returned as it is, and the caller decides what to do. on_retry is a hook for logging. Try it on /v1/flaky; we pass jitter=False so the printed delays are predictable:
log = []
r = request_with_retries(
"GET", f"{BASE}/v1/flaky", params={"key": "demo-2", "fail_times": 2},
jitter=False, on_retry=lambda n, why, delay: log.append((n, why, delay)),
)
print(r.status_code, r.json())
print(log)200 {'ok': True, 'attempt': 3}
[(1, '503', 0.1), (2, '503', 0.2)]It retried twice (after 0.1 s, then 0.2 s) and the third attempt worked. Now two cases where it must give up: a server that keeps failing, and a port with nothing listening:
r = request_with_retries("GET", f"{BASE}/v1/flaky", params={"key": "demo-3", "fail_times": 10},
max_attempts=3, jitter=False)
print("last status:", r.status_code)
try:
r.raise_for_status()
except requests.exceptions.HTTPError as error:
print("gave up:", error.response.status_code)
try:
request_with_retries("GET", "http://localhost:8001/health", max_attempts=2, base=0.05)
except requests.exceptions.ConnectionError:
print("gave up: ConnectionError")last status: 503
gave up: 503
gave up: ConnectionErrorRate limits and Retry-After
Every serious API limits how fast you can call it, and LLM APIs do so by requests per minute and by tokens per minute. The Practice API's /v1/limited allows 3 requests per 10 seconds for each X-Client-Id and then answers 429 with a Retry-After header:
headers = {"X-Client-Id": "nadia-demo"}
for i in range(1, 5):
r = requests.get(f"{BASE}/v1/limited", headers=headers, timeout=TIMEOUT)
print(i, r.status_code, r.json())
wait = int(r.headers["Retry-After"])
print("Retry-After is a whole number of seconds up to 10:", 1 <= wait <= 10)1 200 {'ok': True, 'remaining': 2}
2 200 {'ok': True, 'remaining': 1}
3 200 {'ok': True, 'remaining': 0}
4 429 {'detail': 'Too many requests'}
Retry-After is a whole number of seconds up to 10: TrueNow let request_with_retries deal with it. The fourth call will be answered with 429, the function reads Retry-After, sleeps that long (about ten real seconds here, so be patient), and the retry succeeds:
headers = {"X-Client-Id": "nadia-retry"}
for _ in range(3):
requests.get(f"{BASE}/v1/limited", headers=headers, timeout=TIMEOUT)
waits = []
r = request_with_retries("GET", f"{BASE}/v1/limited", headers=headers,
on_retry=lambda n, why, delay: waits.append((why, delay >= 1)))
print(r.status_code, r.json())
print(waits)200 {'ok': True, 'remaining': 2}
[('429', True)]It waited because the server said so, not because of our own guess. Better still is not to hit the limit at all: spread calls out, cache results you already have, and send fewer, bigger requests where the API allows batching.
Sessions
Every requests.get opens a new connection, which means a new TCP handshake and, for HTTPS, a new TLS handshake. A requests.Session keeps connections open and reuses them, and it carries shared settings: headers, authentication, cookies. For many calls to the same host (paging through results, a chat loop) it is faster and tidier:
session = requests.Session()
session.headers.update({"X-Client-Id": "nadia-session", "Accept": "application/json"})
session.headers["Authorization"] = f"Bearer {os.environ['PRACTICE_TOKEN']}"
echoed = session.get(f"{BASE}/v1/echo", timeout=TIMEOUT).json()["headers"]
print(echoed["accept"], "authorization" in echoed)
session.close()application/json TrueEvery request from this session now carries those headers, and the key is typed once. Close a session when finished (session.close() or with requests.Session() as session:). One thing a session does not do is remember a timeout: you must still pass timeout= on each call, which is another reason to wrap the session in your own client (below).
You do not have to write your own retry loop. requests is built on urllib3, whose Retry class can be mounted on a session. It retries on the status codes you list, backs off, and respects Retry-After:
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
retry = Retry(total=3, backoff_factor=0.05, status_forcelist=[429, 500, 502, 503, 504],
allowed_methods=["GET"], respect_retry_after_header=True)
auto = requests.Session()
auto.mount("http://", HTTPAdapter(max_retries=retry))
auto.mount("https://", HTTPAdapter(max_retries=retry))
r = auto.get(f"{BASE}/v1/flaky", params={"key": "demo-4", "fail_times": 2}, timeout=TIMEOUT)
print(r.status_code, r.json())
try:
auto.get(f"{BASE}/v1/flaky", params={"key": "demo-5", "fail_times": 10}, timeout=TIMEOUT)
except requests.exceptions.RetryError:
print("RetryError: out of retries")200 {'ok': True, 'attempt': 3}
RetryError: out of retriesWhich should you use? The built-in Retry is fine and well tested for plain GETs. A hand-written function gives you control: custom logging, a retry budget, different rules per endpoint, and it is easier to read in a tutorial and to unit-test. Whichever you choose, the rules are the same: only transient failures, a cap on attempts, a growing delay, and a timeout on every attempt.
Saving results to JSON and CSV
An API call costs time, quota and sometimes money. When you fetch data you will use again (a dataset for training, documents for a search index), save it, so a crash later does not force you to start over. Two formats cover most needs: JSON keeps nested structure, and CSV suits flat tables that open in Excel and pandas. We fetch every course, following next_page and using retries:
import csv
courses = []
page = 1
while page:
r = request_with_retries("GET", f"{BASE}/v1/courses", params={"page": page, "per_page": 4})
r.raise_for_status()
data = r.json()
courses.extend(data["items"])
page = data["next_page"]
print(len(courses), "courses fetched")
with open("courses.json", "w", encoding="utf-8") as f:
json.dump(courses, f, indent=2, ensure_ascii=False)
with open("courses.csv", "w", encoding="utf-8", newline="") as f:
writer = csv.DictWriter(f, fieldnames=["id", "title", "level", "hours", "rating"], lineterminator="\n")
writer.writeheader()
writer.writerows(courses)10 courses fetchedhead -3 courses.csv
wc -l courses.csvid,title,level,hours,rating
1,How AI Works,beginner,3,4.7
2,Python for AI,beginner,12,4.8
11 courses.csvDetails that matter: always pass encoding="utf-8" (Bangla text and many symbols break on Windows' default encoding otherwise), ensure_ascii=False keeps non-English characters readable in the JSON file, and newline="" is what the csv module asks for when opening a file. Reading back is symmetrical, and lets a later run skip the network:
with open("courses.json", encoding="utf-8") as f:
again = json.load(f)
print(again == courses)
with open("courses.csv", encoding="utf-8", newline="") as f:
rows = list(csv.DictReader(f))
print(rows[0])
print(type(rows[0]["hours"]).__name__)True
{'id': '1', 'title': 'How AI Works', 'level': 'beginner', 'hours': '3', 'rating': '4.7'}
strNotice that CSV gives everything back as strings; "3" is not 3. JSON keeps numbers as numbers. With pandas, pd.DataFrame(courses).to_csv("courses.csv", index=False) does the CSV part in one line. For big or long-running downloads, write to a temporary file and rename it (os.replace) when finished, so a crash never leaves a half-written file looking complete.
A reusable client
You now have timeouts, retries, a session, a token and pagination, scattered across cells. Put them in one class, so every script in your project makes calls the same safe way. Save this as practice_client.py:
# file: practice_client.py
"""A small, reusable client for the BitByte Practice API."""
import os
import random
import time
from typing import NamedTuple
import requests
RETRY_STATUSES = {429, 500, 502, 503, 504}
class APIError(Exception):
"""The API answered with an error we will not (or can no longer) retry."""
def __init__(self, message, status=None):
super().__init__(message)
self.status = status
class ChatReply(NamedTuple):
text: str
usage: dict
class PracticeClient:
def __init__(self, base_url=None, token=None, timeout=(3.05, 30), max_attempts=4,
backoff=0.1, jitter=0.25, sleep=time.sleep):
self.base_url = (base_url or os.environ["PRACTICE_BASE_URL"]).rstrip("/")
self.timeout = timeout
self.max_attempts = max_attempts
self.backoff = backoff
self.jitter = jitter
self._sleep = sleep
self.session = requests.Session()
self.session.headers["Accept"] = "application/json"
token = token or os.environ.get("PRACTICE_TOKEN")
if token:
self.session.headers["Authorization"] = f"Bearer {token}"
self.calls = 0
self.usage = {"prompt_tokens": 0, "completion_tokens": 0, "total_tokens": 0}
def __enter__(self):
return self
def __exit__(self, *exc_info):
self.session.close()
def _delay(self, attempt, response=None):
delay = min(5.0, self.backoff * 2 ** (attempt - 1))
delay *= 1 + random.uniform(0, self.jitter)
header = response.headers.get("Retry-After", "") if response is not None else ""
if header.isdigit():
delay = max(delay, min(int(header), 30))
return delay
@staticmethod
def _detail(response):
try:
return response.json()["detail"]
except (ValueError, KeyError, TypeError):
return response.text[:100]
def request(self, method, path, **kwargs):
"""Send a request with retries; return the parsed JSON or raise APIError."""
url = f"{self.base_url}{path}"
kwargs.setdefault("timeout", self.timeout)
for attempt in range(1, self.max_attempts + 1):
last = attempt == self.max_attempts
try:
response = self.session.request(method, url, **kwargs)
except (requests.exceptions.ConnectionError, requests.exceptions.Timeout) as error:
if last:
raise APIError(f"{method} {path} failed: {type(error).__name__}") from error
self._sleep(self._delay(attempt))
continue
if response.status_code in RETRY_STATUSES and not last:
self._sleep(self._delay(attempt, response))
continue
if not response.ok:
message = f"{method} {path} -> {response.status_code}: {self._detail(response)}"
raise APIError(message, response.status_code)
return response.json()
def get(self, path, **params):
return self.request("GET", path, params=params)
def courses(self, **filters):
"""Yield every course, following next_page."""
page = 1
while page:
data = self.get("/v1/courses", page=page, per_page=4, **filters)
yield from data["items"]
page = data["next_page"]
def chat(self, messages, model="practice-llm-1"):
"""Send a conversation (non-streaming) and return a ChatReply."""
data = self.request("POST", "/v1/chat", json={"model": model, "messages": messages})
usage = data["usage"]
self.calls += 1
for name in self.usage:
self.usage[name] += usage[name]
return ChatReply(data["message"]["content"], usage)The shape is what matters. The base URL and token come from the environment (or constructor arguments, which make tests easy), one Session is shared, one request method owns timeouts, retries and error translation, and everything else (get, courses, chat) is a thin layer over it. Callers see one exception type, APIError, with the status code attached. The sleep argument lets a test pass a fake that does not really wait. Use it from the next block:
from practice_client import APIError, PracticeClient
waits = []
client = PracticeClient(jitter=0, sleep=waits.append)
print(client.get("/health"))
print(client.get("/v1/flaky", key="demo-6", fail_times=2))
print("waited between retries:", waits)
try:
client.get("/v1/courses/99")
except APIError as error:
print(error, "| status", error.status, "| waits unchanged:", waits)
print([c["title"] for c in client.courses(level="intermediate")]){'status': 'ok'}
{'ok': True, 'attempt': 3}
waited between retries: [0.1, 0.2]
GET /v1/courses/99 -> 404: Course 99 not found | status 404 | waits unchanged: [0.1, 0.2]
['Prompt Engineering', 'LLM APIs']The 503s were retried and the 404 was not. All call sites now share one policy: if you later change the retry rules, you change one method.
Calling an LLM-style chat API
A hosted LLM is, from your code's point of view, an HTTP API: a POST with a JSON body, an Authorization: Bearer … header, and a JSON answer. The Practice API's /v1/chat is a fake LLM with the same shape (its answers are predictable). First the raw request, so you see exactly what travels:
token = os.environ["PRACTICE_TOKEN"]
body = {"model": "practice-llm-1", "messages": [{"role": "user", "content": "What is an API?"}]}
r = requests.post(f"{BASE}/v1/chat", json=body, headers={"Authorization": f"Bearer {token}"},
timeout=(3.05, 60))
print(r.status_code)
print(json.dumps(r.json(), indent=2))200
{
"model": "practice-llm-1",
"message": {
"role": "assistant",
"content": "This is a practice answer about: What is an API. A real model would say more."
},
"usage": {
"prompt_tokens": 4,
"completion_tokens": 16,
"total_tokens": 20
}
}Three things to notice. messages is a list of {"role", "content"} turns; roles are system (instructions for behaviour), user and assistant. The answer is under message.content. And usage says how many tokens went in and came out. The read timeout here is long (60 s) because real models take seconds to minutes to produce an answer; the connect timeout stays short. Real providers differ in field names but not in the idea:
| API | Answer text | Token usage |
|---|---|---|
Practice API /v1/chat | message.content | usage.prompt_tokens, usage.completion_tokens |
| OpenAI Chat Completions | choices[0].message.content | usage.prompt_tokens, usage.completion_tokens |
| OpenAI Responses (recommended for new projects) | output_text in the SDK, items under output | usage.input_tokens, usage.output_tokens |
| Anthropic Messages | content[0].text (a list of blocks) | usage.input_tokens, usage.output_tokens |
Because the field names differ, put the provider behind your own function (chat(messages) -> ChatReply), exactly like PracticeClient.chat above, so changing providers touches one file. The same errors apply as everywhere: no token gives 401, and a wrong token gives 401 too; neither is retried:
for bad in (None, "token-wrong"):
anonymous = PracticeClient(token=bad, sleep=waits.append)
anonymous.session.headers.pop("Authorization", None)
if bad:
anonymous.session.headers["Authorization"] = f"Bearer {bad}"
try:
anonymous.chat([{"role": "user", "content": "hi"}])
except APIError as error:
print(error.status, error)401 POST /v1/chat -> 401: Missing bearer token
401 POST /v1/chat -> 401: Invalid or expired tokenConversations are stateless
A chat API remembers nothing between calls. To have a conversation you send the whole history each time: your system message, every earlier user message and every earlier answer. That is why chat applications keep a list and append to it:
history = [{"role": "system", "content": "You are a concise tutor."}]
for question in ["What is an API?", "Why use timeouts?", "What is a retry?"]:
history.append({"role": "user", "content": question})
reply = client.chat(history)
history.append({"role": "assistant", "content": reply.text})
print(reply.usage["prompt_tokens"], reply.usage["completion_tokens"], "|", reply.text)
print(client.calls, "calls, totals:", client.usage)9 16 | This is a practice answer about: What is an API. A real model would say more.
28 15 | This is a practice answer about: Why use timeouts. A real model would say more.
47 16 | This is a practice answer about: What is a retry. A real model would say more.
3 calls, totals: {'prompt_tokens': 84, 'completion_tokens': 47, 'total_tokens': 131}Look at the first number on each line: prompt_tokens grows with every turn, because earlier turns are sent again and billed again. (The practice API counts words; real providers count tokens, pieces of words, using a tokenizer. English averages roughly three quarters of a word per token, and languages like Bangla usually need more tokens per word, so the same text can cost more.) Long conversations get expensive and eventually exceed the model's context window, so real applications trim old turns, summarise them, or cache the stable beginning of the prompt.
Token and cost awareness
LLM providers bill by tokens, with different prices for input and output, and output is usually several times more expensive. A cost estimate is just arithmetic over the usage numbers. The prices below are examples; always read the provider's current pricing page.
PRICE_PER_MILLION = {"input": 2.00, "output": 10.00} # example USD prices
def estimate_cost(usage, price=PRICE_PER_MILLION):
return (usage["prompt_tokens"] * price["input"]
+ usage["completion_tokens"] * price["output"]) / 1_000_000
per_call = estimate_cost(client.usage) / client.calls
print(f"cost of the conversation: ${estimate_cost(client.usage):.6f}")
print(f"if 1000 users make 30 such calls a month: ${per_call * 1000 * 30:.2f}")cost of the conversation: $0.000638
if 1000 users make 30 such calls a month: $6.38Habits that keep bills predictable:
- Log
usageon every call (with a user id and feature name), so you can answer "where did the money go?". - Set
max_tokens(or the provider's equivalent) to cap the answer length, and ask for short answers when short is enough. - Trim the history you resend, and put big, unchanging text (instructions, documents) at the start so provider-side prompt caching can discount it.
- Use the smallest model that does the job for simple tasks like classification; keep the big one for hard questions.
- Retries cost money too. A retried LLM call is billed again if it ran. Cap attempts and do not retry 4xx errors.
- Set budgets and alerts in the provider's dashboard, and a per-user limit in your own backend.
Real provider SDKs (not run here)
For a real provider you normally use its official SDK instead of raw requests. The SDK builds the request, parses the response into objects, and retries transient errors by itself (the default is two retries, configurable with max_retries), with a timeout setting you should still choose. The key is read from an environment variable, so it never appears in code. These blocks need an account, a paid key and the internet, so they are shown but not run. Anthropic's Messages API:
# pip install anthropic (needs ANTHROPIC_API_KEY in the environment)
import anthropic
client = anthropic.Anthropic(timeout=60.0, max_retries=2) # reads ANTHROPIC_API_KEY itself
message = client.messages.create(
model="claude-sonnet-5-5", # model names change: check the provider's model list
max_tokens=1024, # always cap the answer length
system="You are a concise tutor.",
messages=[{"role": "user", "content": "What is an API?"}],
)
print(message.content[0].text)
print(message.usage.input_tokens, message.usage.output_tokens)OpenAI's Responses API has the same overall shape with different names:
# pip install openai (needs OPENAI_API_KEY in the environment)
from openai import OpenAI
client = OpenAI(timeout=60.0, max_retries=2) # reads OPENAI_API_KEY itself
response = client.responses.create(
model=os.environ["OPENAI_MODEL"], # choose a current model from the provider's docs
instructions="You are a concise tutor.",
input="What is an API?",
max_output_tokens=1024,
)
print(response.output_text)
print(response.usage.input_tokens, response.usage.output_tokens)Compare both with PracticeClient.chat: a key from the environment, a timeout, a cap on output, a list of messages in, text and token counts out. That is why writing your own thin chat() function around any of them is worth it. Never paste a real key into a script, a notebook or a chat; a leaked key is billed to you.
Real-world use
- Batch jobs: classify or summarise ten thousand documents with an LLM. Without retries and saved progress, one 429 at document 8,000 ruins the run; with them, it resumes.
- Backends: your FastAPI service calls a model provider on every user request; its client class, timeouts and usage logging are exactly what you wrote here.
- Cost control: token usage per feature and per user is the first dashboard every AI product team builds.
Common mistakes
- Retrying everything. A
401or422will never fix itself; retrying it wastes time and, on paid APIs, money. Retry only transient failures. - Retrying forever, or instantly. No cap means an endless loop, and no delay hammers a struggling server. Cap attempts, back off, add jitter.
- Ignoring
Retry-After. The server told you exactly when to come back. Obey it (with a sensible upper limit). - Retrying unsafe POSTs. A repeated "create order" can create two orders. Retry only when a duplicate is harmless or an idempotency key protects you.
- Forgetting that history is re-sent. Costs grow with every turn. Trim, summarise and cap
max_tokens. - No usage logging. If you do not record tokens per call, a runaway loop shows up first on the invoice.
- Keys in code. Read keys from the environment; never commit or print them.
Try it yourself
- Easy: Print the backoff delays for attempts 1 to 5 with
base=0.5andcap=4. - Easy: Use
PracticeClientto print the titles of allbeginnercourses with more than 8 hours, sorted by hours. - Medium: Call
/v1/flakywithfail_times=3usingrequest_with_retriestwice: once withmax_attempts=3(keyex-1), once withmax_attempts=5(keyex-2). Print the final status each time. - Medium: Ask the chat API three questions (single-turn each), save the question, answer and token counts to
answers.json, and print how many records the file holds and the total tokens. - Hard: Write
BudgetClient, a subclass ofPracticeClientthat takesmax_total_tokensand raisesAPIError("token budget exceeded")before a chat call once the running total has reached the budget. Show it stopping a loop of questions with a budget of 40.
Answers
# 1. delays
print([backoff_delay(n, base=0.5, cap=4) for n in range(1, 6)])
# 2. long beginner courses
long_ones = [c for c in client.courses(level="beginner") if c["hours"] > 8]
for c in sorted(long_ones, key=lambda c: c["hours"]):
print(c["hours"], c["title"])[0.5, 1.0, 2.0, 4, 4]
9 Git, APIs and Backend
10 SQL and Data Handling
12 Python for AI# 3. give up vs keep going
a = request_with_retries("GET", f"{BASE}/v1/flaky", params={"key": "ex-1", "fail_times": 3},
max_attempts=3, jitter=False, base=0.05)
b = request_with_retries("GET", f"{BASE}/v1/flaky", params={"key": "ex-2", "fail_times": 3},
max_attempts=5, jitter=False, base=0.05)
print(a.status_code, b.status_code, b.json())
# 4. save answers
records = []
for question in ["What is a token?", "What is a timeout?", "What is JSON?"]:
reply = client.chat([{"role": "user", "content": question}])
records.append({"question": question, "answer": reply.text, **reply.usage})
with open("answers.json", "w", encoding="utf-8") as f:
json.dump(records, f, indent=2, ensure_ascii=False)
with open("answers.json", encoding="utf-8") as f:
saved = json.load(f)
print(len(saved), sum(r["total_tokens"] for r in saved))503 200 {'ok': True, 'attempt': 4}
3 58# 5. a token budget
class BudgetClient(PracticeClient):
def __init__(self, max_total_tokens, **kwargs):
super().__init__(**kwargs)
self.max_total_tokens = max_total_tokens
def chat(self, messages, model="practice-llm-1"):
if self.usage["total_tokens"] >= self.max_total_tokens:
raise APIError("token budget exceeded")
return super().chat(messages, model)
budgeted = BudgetClient(40)
for number in range(1, 10):
try:
reply = budgeted.chat([{"role": "user", "content": f"Question number {number}"}])
except APIError as error:
print(f"stopped before call {number}:", error, budgeted.usage["total_tokens"])
breakstopped before call 4: token budget exceeded 54
Summary
- Retry only transient failures: connection errors, timeouts, 429, 500, 502, 503, 504. Never retry 4xx mistakes of your own.
- Use exponential backoff with a cap and jitter, a maximum number of attempts, and obey
Retry-After. Take care when retrying POST. requests.Sessionreuses connections and shares headers; urllib3'sRetryis a built-in alternative to a hand-written loop.- Save fetched data to JSON (keeps structure) or CSV (flat tables) with
encoding="utf-8". - Wrap timeouts, retries, auth and error translation in one client class with a single exception type.
- Chat APIs are stateless: you resend the history, and tokens (and cost) grow with it. Log
usage, capmax_tokens, and read the provider's pricing.
Next: What a Backend Does: Requests, Routes and Responses turns around: instead of calling other people's servers, you will start to build your own.

