requests
cheat sheet
The requests library at a glance: verbs, params, JSON, sessions, auth, timeouts, retries, streaming, uploads and errors.
- Version
- v2.34.2
- Snippets
- 81
- Sections
- 11
Version notes · requests 2.34.2
- 2.34 ships its own type hints: drop
types-requestsfrom your dev dependencies. - 2.34:
Response.reasonis typedstr(no longerNone), andResponse.historyno longer contains the response itself. - 2.33 fixed CVE-2026-25645 in
requests.utils.extract_zipped_paths. Upgrade if you call it directly. - Needs Python 3.10+. There is still no default timeout: always pass
timeout=.
The most used Python HTTP client: a small, synchronous API on top of urllib3, with connection pooling, sessions, cookies and automatic decoding.
Tiny API
get, post, json(): done
Sessions
pooling, cookies, shared headers
TLS by default
verified with certifi
Sync only
need async? see httpx
Quick start
uv add requestsuv run python -c "import requests; print(requests.get('https://httpbin.org/get', timeout=5).json())"- Add to a project
- SOCKS proxy support
- Plain pip
- Import
- Installed version
- For retries & pool sizes
- GET
- POST a JSON body
- PUT
- PATCH
- DELETE
- Headers only (no redirects by default)
- OPTIONS
- Any method by name
Top-level helpers open a new connection every time. Making several calls to one host? Use a Session.
URL & headers
?q=uv&page=2, URL-encoded- Repeated key:
?tag=a&tag=b - Custom headers
- Bearer token
- Send cookies
Body
- JSON body +
Content-Typeheader - Form-encoded body
- Raw body as-is
- Multipart upload
- Set filename + content type
200,404…Truefor status < 400- Raise
HTTPErrorfor 4xx / 5xx - Parse JSON body
- Body as
str(decoded withr.encoding) - Body as
bytes - Headers (case-insensitive)
- Final URL, after redirects
- Redirect responses, oldest first
- Time until headers arrived
- Cookies set by the server
- Parsed
Linkheader (pagination) - What was actually sent
- Pooled connections, closed on exit
- Headers for every request
- Auth for every request
- Query params for every request
- CA bundle for every request
- Same verbs as the module
- Cookies persist across calls
- Bigger connection pool (threads)
client.py
import requestsfrom requests.adapters import HTTPAdapterfrom urllib3.util import Retryretry = Retry( total=5, backoff_factor=0.5, status_forcelist=[429, 502, 503],)s = requests.Session()s.mount("https://", HTTPAdapter(max_retries=retry))s.headers["User-Agent"] = "my-app/1.0"r = s.get(url, timeout=(3, 30))r.raise_for_status()print(r.json())Session settings (headers, auth, params) merge with the ones you pass per request; per-request values win.
- HTTP Basic
- Digest auth class
- HTTP Digest
- Bearer / OAuth token
- Custom auth: implement
__call__(self, r) - Ignore
~/.netrcand proxy env vars
Without auth=, requests reads credentials for the host from ~/.netrc. Auth headers are dropped when a redirect leaves the host.
Timeouts
- Connect and read timeout, seconds
- (connect, read) separately
- Wait forever (the default!)
Retries
- Retry policy (urllib3)
- Exponential backoff
- Also retry these statuses
- Retry POST too (not idempotent!)
- Attach to a session with
mount
The read timeout is the gap between bytes, not the total time: a slow trickle never times out. Retries honour the Retry-After header.
- Don’t load the body into memory
- Body in chunks (decompressed)
- Line by line (NDJSON, logs)
- Raw socket bytes to a file (not decompressed)
- Size for a progress bar
- Stream an upload from an open file
- Chunked upload from a generator
download.py
with requests.get(url, stream=True, timeout=30) as r: r.raise_for_status() with open("big.zip", "wb") as f: for chunk in r.iter_content( chunk_size=65536): f.write(chunk)- Base class: catches everything below
- From
raise_for_status() - Status of the failed response
- DNS failure, refused, reset
- Connect or read timeout
- Read timeout only (
ConnectTimeouttoo) - More than 30 redirects
r.json()on a non-JSON body
4xx / 5xx responses don’t raise on their own. Call r.raise_for_status(), or check r.ok.
- Custom CA bundle
- Skip TLS checks (testing only)
- Client certificate (mTLS)
- Proxy per scheme
- Don’t follow redirects
- Lower the redirect limit (30)
Environment variables
- Proxy (also
HTTP_PROXY,ALL_PROXY) - Hosts that skip the proxy
- CA bundle (
CURL_CA_BUNDLEalso works)
- Raise on every 4xx / 5xx
- Session-wide hook
- The body that was sent
- Log connections & retries
- Print raw request / response headers
