Connection reuse
Several calls target the same host and should benefit from reusable connections.
Requests · Class
A Requests Session groups HTTP calls while persisting selected settings and cookies. It also provides connection pooling and can be used as a context manager for automatic cleanup.
Session groups repeated HTTP requests while retaining configuration and cookies between them. It also uses connection pooling, and its context-manager form closes the session when the block ends.
requests.Session()import requests
with requests.Session() as session:
session.headers.update({"Accept": "application/json"})
response = session.get("https://httpbin.org/get", timeout=10)
response.raise_for_status()
print(response.json()["url"])Creates a session, applies a default header, performs a request, and closes the session automatically.
Several calls target the same host and should benefit from reusable connections.
Multiple requests share authentication, headers, or other defaults.
A workflow needs cookies from one response to be sent on later requests.
A short-lived request workflow should release resources automatically.
A Session persists selected request settings and cookies across requests. It also uses urllib3 connection pooling, allowing connections to the same host to be reused.
Follow-up: How should session-wide and request-specific headers interact? Session headers provide defaults, while headers supplied to an individual request can add or override them.
Yes. A Session has the methods of the main Requests API, so it can issue GET, POST, and other HTTP requests through the session object. This lets shared state and configuration apply consistently.
Follow-up: How can a session be safely bounded? Use with requests.Session() as session: so the session is closed when the block exits.
Use with requests.Session() as session: when the session should be scoped to a block. This context-manager pattern ensures the session is closed after the block completes.
Follow-up: What state remains useful during that block? Cookies and configured defaults are available to subsequent requests made through the same session.
requests.Requestrequests.Responserequests.Session.cookiesrequests.adapters.HTTPAdapterrequests.sessions.session