python 30 lines · 7 steps

Building a resilient requests Session

A reusable HTTP session with automatic retries and backoff keeps flaky API calls from failing on the first hiccup.

Explained by highlit
1import requests
2from requests.adapters import HTTPAdapter
3from urllib3.util.retry import Retry
4 
5 
6def build_session() -> requests.Session:
7 session = requests.Session()
8 retries = Retry(
9 total=4,
10 backoff_factor=0.5,
11 status_forcelist=(429, 500, 502, 503, 504),
12 allowed_methods=frozenset({"POST", "GET"}),
13 raise_on_status=False,
14 )
15 adapter = HTTPAdapter(max_retries=retries)
16 session.mount("https://", adapter)
17 session.mount("http://", adapter)
18 session.headers.update({"User-Agent": "billing-sync/1.0"})
19 return session
20 
21 
22def submit_invoice(session: requests.Session, invoice: dict, token: str) -> dict:
23 response = session.post(
24 "https://api.acme.example/v2/invoices",
25 json=invoice,
26 headers={"Authorization": f"Bearer {token}"},
27 timeout=(3.05, 27),
28 )
29 response.raise_for_status()
30 return response.json()
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Configuring retries at the adapter level means every request through the session inherits the same resilience policy.
  2. 2Exponential backoff with a status_forcelist retries only transient failures instead of blindly hammering the server.
  3. 3Always pair requests with explicit connect and read timeouts so a hung server can't stall your process indefinitely.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Building a resilient requests Session — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code