Every Python developer has typed requests.get(url) a thousand times, and almost nobody has opened the package. That is the whole trick of the library: a four-word facade over a surprisingly disciplined engine. When the facade leaks — a ConnectionError that is not the built-in one, an Authorization header that vanished after a redirect, a socket pool that stalls at ten connections — you are debugging blind unless you know what lives underneath. This tour walks the real source tree of psf/requests at version 2.34.2, module by module, so the next leak has a name and a line number.
The engine is small in file count but dense in contracts: 19 Python modules under src/requests, each with a narrow job. sessions.py owns state, models.py owns the wire format, adapters.py is the wall where your PreparedRequest becomes a urllib3 call, and auth.py, cookies.py, hooks.py plug into that flow through callable protocols. Nothing is magic; every convenience keyword argument you pass to get() or post() is merged, prepared, and translated in a fixed, traceable order.
What follows is a two-level map. The overview shows the object graph: who creates whom, who talks to whom. The detail graph drills into the exact call sequence from Session.request down to conn.urlopen, including the redirect loop and the urllib3 exception translation layer. Every symbol cited below links to the real line in the repository on branch main, so you can verify each claim as you read.
The requests object graph: module-level helpers create a throwaway Session, the Session prepares a PreparedRequest and hands it to a mounted HTTPAdapter, which talks to urllib3's PoolManager; auth, hooks, cookies and the exception tree wrap around the flow.
Reading the overview from left to right:
- api.request, L24 — every module-level helper builds a
Sessioninside awithblock and closes it, which is whyrequests.get()never leaks sockets but also never reuses connections. - Session, L395 — the durable object; its constructor mounts two
HTTPAdapter()instances forhttps://andhttp://at L502 and wires a defaultRequestsCookieJar. - Session.prepare_request, L511 — folds request kwargs over session defaults via
merge_setting(L76) andmerge_hooks(L108); a value ofNoneexplicitly deletes a key rather than keeping the default. - PreparedRequest.prepare, L424 — a fixed preparation order: method, url, headers, cookies, body, then auth last, so OAuth-style schemes mutate the final bytes.
- Session.get_adapter, L870 — picks the adapter by case-insensitive URL prefix;
mountkeeps the registry sorted by descending prefix length (L888), and a miss raisesInvalidSchema. - HTTPAdapter.init_poolmanager, L239 — creates the urllib3
PoolManagerwithnum_pools=pool_connections, maxsize=pool_maxsize, both defaulting to 10 (constants at L79–82). - HTTPAdapter.build_response, L365 — wraps the raw urllib3 response: status via
getattr, headers into aCaseInsensitiveDict, cookies extracted from the underlying HTTP message. - dispatch_hook, L32 —
responseis the only hook event in the system (HOOKSat L22), and a hook returning a non-None value replaces the response object outright. - AuthBase, L78 — auth is just a callable that mutates a
PreparedRequest;HTTPDigestAuthregisters ahandle_401response hook (L273) so challenges trigger an automatic resend.
The detail view traces one call from api.request down to conn.urlopen and back: preparation steps in models.py, the redirect generator in SessionRedirectMixin, cookie persistence, and the urllib3-to-requests exception dictionary in adapters.py.
The Session: where your kwargs become bytes
Session.request at sessions.py L557 is four moves: build a Request object, call prepare_request, merge environment settings, and delegate to send. The merge step is where most confusion dies: merge_environment_settings at L831 consults REQUESTS_CA_BUNDLE or CURL_CA_BUNDLE from the environment (L857–859) when trust_env is on, then applies the same request-wins-over-session rule as merge_setting. Passing verify=False on one call genuinely disables TLS verification for that call only — the session default survives.
Session.send at L752 is the runtime guard post. It rejects a bare Request with ValueError("You can only send PreparedRequests.") at L768, stamps r.elapsed using preferred_clock — perf_counter on Windows, time.time elsewhere (L70–73) — dispatches response hooks at L791, persists cookies at L799, and only then walks resolve_redirects (L804). If stream=False, it forces r.content at L827 so the socket is drained and returned to the pool before you get the response back. That single line is the difference between a clean keep-alive and a dangling connection.
HTTPAdapter: the urllib3 wall and its exception dictionary
The adapter is the only place that knows urllib3. HTTPAdapter.send at adapters.py L634 acquires a connection through get_connection_with_tls_context (L455) — the modern entry point replacing the deprecated get_connection (L512), a breaking surface for custom adapter subclasses since Requests 2.32.2, as its DeprecationWarning cites PR #6710. The pool key comes from build_connection_pool_key_attributes (L403): scheme, host, port plus SSL kwargs (ca_certs, ca_cert_dir, cert_reqs, client cert files) computed by _urllib3_request_context (L85). Then cert_verify (L307) falls back to DEFAULT_CA_BUNDLE_PATH, which resolves to certifi’s bundle via utils.py L82.
The urlopen call at L696 passes redirect=False, preload_content=False, decode_content=False: requests deliberately owns redirects, streaming and decoding itself, using urllib3 only for the single hop. The try block after it (L710–746) is the library’s real error contract: ProtocolError and OSError become ConnectionError; MaxRetryError becomes ConnectTimeout, RetryError, ProxyError or SSLError depending on e.reason; ClosedPoolError and read-timeout variants each map to their requests-side twin. Retry behavior is configured once in the constructor: max_retries=DEFAULT_RETRIES becomes Retry(0, read=False) at L209 — zero retries for anything that reached the server, despite the docstring’s warning that only DNS/socket/connect failures are ever retried.
Redirects, cookies, and the auth you must not leak
The redirect machine lives in SessionRedirectMixin. resolve_redirects at sessions.py L186 is a generator that consumes the previous response’s socket (L212), closes it back into the pool (L222), raises TooManyRedirects past max_redirects — DEFAULT_REDIRECT_LIMIT is 30 at models.py L103 — and purges Content-Length, Content-Type and Transfer-Encoding plus the body for every hop unless the status is 307/308 (L250–258). Method rewriting follows browsers, not RFC nostalgia: rebuild_method (L370) turns 303 and 302 into GET (except HEAD) and turns a 301’d POST into GET, a behavior kept for compatibility since issue 1704.
Credential safety is explicit rather than implied. should_strip_auth (L154) drops Authorization when hostname, scheme or port changes, but deliberately allows an http://:80 to https://:443 upgrade to keep credentials. rebuild_proxies (L334) re-resolves per-hop proxies and only attaches Proxy-Authorization to non-TLS tunnels. Cookies travel across the chain through extract_cookies_to_jar at cookies.py L135, which adapters PreparedRequest and the raw response into the http.cookiejar interface via MockRequest (L31) and MockResponse (L114). The public RequestsCookieJar (L191) layers a dict API over the jar; its docs are honest that lookups are O(n) and _find_no_duplicates (L423) raises CookieConflictError when a name is ambiguous across domains.
From Retry(0, read=False) to 0x023402: the numbers in the code
The package version is machine-readable: __version__.py sets __version__ = "2.34.2" and __build__ = 0x023402 (L8–9), a hex-encoded version number. The whole repository tracks only 130 files, of which src/requests holds 19 Python modules plus a py.typed marker — the library has grown almost no new source files in over a decade, by design.
Dependency bounds are strict and asserted at import time: pyproject.toml pins urllib3>=1.26,<3, charset_normalizer>=2,<4, idna>=2.5,<4 and certifi>=2023.5.7 (L18–22), while check_compatibility in __init__.py (L60) re-verifies at runtime and warns with RequestsDependencyWarning if urllib3 is older than 1.21.1 or the charset detector is out of range. The legacy requests.packages.urllib3 import path is kept alive by a sys.modules aliasing loop in packages.py L8, so code written against 2013-era imports still resolves to the real modules.
Constant choices encode policy. Chunked reads use CONTENT_CHUNK_SIZE = 10 * 1024 and ITER_CHUNK_SIZE = 512 (models.py L104–105); CaseInsensitiveDict in structures.py L20 stores an OrderedDict keyed by lowercase while remembering the last-cased spelling, so headers['content-encoding'] works but iteration shows what the server sent. Status codes are a single _codes dictionary expanded by a _init() setattr loop (status_codes.py L109) into a LookupDict, giving you codes.not_found without any code generation step. The test matrix is equally compact: tox.ini runs pytest {posargs:tests} across py310–py314 in a default and a use_chardet_on_py3 flavor — the same pytest suite that CI drives, with coverage config reduced to a one-line .coveragerc omitting the legacy shim, a setup familiar from coveragepy, and linting enforced by a .pre-commit-config.yaml running ruff-check and ruff-format hooks of the same pre-commit framework used across the Python ecosystem.
Errors as a public API
The exception module is a contract, not an afterthought. Everything inherits from RequestException(IOError) at exceptions.py L20, which accepts request= and response= kwargs so callers can always recover the failing exchange. Multiple inheritance is used precisely: ConnectTimeout(ConnectionError, Timeout) (L91) lets you catch either the family or the phase, and MissingSchema, InvalidSchema, InvalidURL and InvalidHeader also subclass ValueError because they represent caller mistakes. Even the JSON path gets a diamond: JSONDecodeError(InvalidJSONError, CompatJSONDecodeError) (L42) carries a custom __reduce__ so pickling uses the underlying json library’s signature rather than the IOError one.
Response.raise_for_status at models.py L1144 raises HTTPError only for 4xx and 5xx, decoding byte reason strings defensively. And the streaming surface wraps urllib3 failures at the consumption boundary: inside iter_content (L914), a ProtocolError becomes ChunkedEncodingError, DecodeError becomes ContentDecodingError, and ReadTimeoutError becomes ConnectionError (L940–947) — meaning a timeout can surface from a body read you thought had already succeeded, several lines after the request “returned.”
Honest Limits
This design has real ceilings. It is a synchronous client: no HTTP/2, no async, no native websockets — the library deliberately refuses to grow transport ambitions, delegating everything beyond HTTP/1.1 single hops to urllib3. Pool sizing defaults are conservative; with Enjoyed this post? Never miss out on future posts by following us pool_connections=10 and pool_maxsize=10 (adapters.py L80), a high-fanout scraper can exhaust the pool and block unless you mount a tuned HTTPAdapter yourself. Digest auth implements auth qop only — the XXX handle auth-int comment at auth.py L247 marks a gap RFC 2617 allows. prepare_cookies is documented to be effective only once per PreparedRequest (models.py L699 docstring), a footgun for anyone reusing prepared objects. And since 2.32.2, custom HTTPAdapter subclasses overriding the old get_connection emit DeprecationWarning and must migrate to get_connection_with_tls_context. Where the project does keep quality high is hygiene: the pytest-driven suite in tests/ exercises redirects, proxies and TLS with a local test server, coverage tracks it, and pre-commit gates every patch — infra patterns this site has covered separately for pytest, coveragepy and pre-commit.