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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Configuring retries at the adapter level means every request through the session inherits the same resilience policy.
- 2Exponential backoff with a status_forcelist retries only transient failures instead of blindly hammering the server.
- 3Always pair requests with explicit connect and read timeouts so a hung server can't stall your process indefinitely.
Related explainers
java
@Service public class InventoryService { private final RestClient warehouseClient;
Bulkhead-protected HTTP calls in Spring
bulkhead
resilience
fallback
Intermediate
7 steps
python
from itertools import cycle from collections import defaultdict
Round-robin task distribution in Python
round-robin
iterators
load-balancing
Intermediate
6 steps
python
import base64 import json from typing import Annotated, Optional
Cursor pagination in a FastAPI endpoint
pagination
cursor
async
Intermediate
9 steps
python
import secrets from fastapi import Depends, FastAPI, HTTPException, Security, status from fastapi.security import APIKeyHeader
API key authentication as a FastAPI dependency
authentication
dependency-injection
api-keys
Intermediate
8 steps
python
import hashlib from collections import defaultdict from pathlib import Path
Finding duplicate files by size then hash
hashing
file-io
deduplication
Intermediate
7 steps
python
from flask import Flask, request, g, jsonify from flask_babel import Babel, gettext as _, format_datetime from datetime import datetime
Per-request localization in Flask with Babel
i18n
content-negotiation
request-lifecycle
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/building-a-resilient-requests-session-explained-python-636b/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.