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
python
from datetime import datetime, date from decimal import Decimal from flask import Flask, jsonify from flask.json.provider import DefaultJSONProvider
Serializing SQLAlchemy models in Flask JSON
serialization
orm
json
Intermediate
6 steps
go
package payments import ( "context"
Fetching a charge over HTTP in Go
context-timeout
http-client
json-decoding
Intermediate
6 steps
python
from datetime import datetime from fastapi import APIRouter, Depends, HTTPException, status from pydantic import BaseModel, ConfigDict, EmailStr from sqlalchemy.orm import Session
Building a users router in FastAPI
routing
serialization
dependency-injection
Intermediate
7 steps
python
import json from dataclasses import dataclass, field, asdict from datetime import datetime from typing import Any
JSON round-tripping with Python dataclasses
dataclasses
serialization
json
Intermediate
6 steps
php
<?php namespace App\Services;
Resilient HTTP retries with Laravel's client
http-client
retry-logic
error-handling
Intermediate
7 steps
python
import re from django.core.exceptions import ValidationError from django.core.validators import RegexValidator
Building a deconstructible validator in Django
validation
regex
deconstructible
Intermediate
7 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.