Thuta Learning
Python
AdvancedProgrammingBeginner

Requests Library

PythonLesson 4830 min

What you'll walk away with

  • Explain why a Session beats repeated requests.get() calls when you send many requests
  • Use params= and timeout=(connect, read) correctly
  • Relate ConnectionError, Timeout, HTTPError and RequestException and catch them in the right order
  • Attach an adapter with session.mount() for retries or offline testing

Explain it simply

Explain it simply

Each call to requests.get() is like phoning a company, giving your name and account number from scratch, then hanging up. That is fine for one or two questions, but with hundreds of them most of the time goes on the introductions.

A requests.Session keeps the line open and remembers your details after you give them once. It reuses headers, cookies and network connections for every request, so the code gets shorter and the program gets faster.

Problem → Why → Solution

The problem: requests.get() in a loop, with verify=False

The script below downloads 500 pages of items. Every request opens a new connection and repeats the TLS handshake, which is slow, and the headers are repeated each time. Worse, someone "fixed" a certificate error with verify=False, which opens the door to man-in-the-middle attacks. There is no timeout and no status check either.

download_items.py
import requests

items = []
for page in range(1, 501):
    r = requests.get(f"https://api.example.com/items?page={page}",
                     headers={"Authorization": f"Bearer {TOKEN}"},
                     verify=False)          # silences the SSL error... and the safety
    items.extend(r.json())                  # no timeout, no status check

Why is this slow and unsafe?

The module-level requests.get() creates a fresh Session for every call and throws it away, so keep-alive connections are never reused. verify=False skips certificate checks entirely, so anyone on the network path can impersonate the server and steal the Bearer token. One Session, one timeout and one raise_for_status() fix all of it.

Core concept: sessions, timeouts and exceptions

requests.Session() keeps state between requests. Headers added with session.headers.update(...), cookies set by the server and session.auth are sent automatically on every request, and underneath, a urllib3 connection pool reuses connections to the same host. session.get(), post(), put(), patch() and delete() accept the same arguments as the module functions. Writing with requests.Session() as session: closes the connections at the end.

params= URL-encodes a dict and appends it as the query string: spaces become + and characters such as & are escaped. timeout=5 is not a five-second total; it limits connecting and waiting between bytes from the server (reading) separately. A tuple such as timeout=(3.05, 10) sets the connect and read timeouts independently. TLS certificates are verified by default; for a company's internal CA pass verify="/path/to/ca.pem", never False.

The Response object you get back has attributes worth knowing. response.ok is True when the status is below 400, and response.headers is a case-insensitive dict, so headers["content-type"] and headers["Content-Type"] are the same. response.content is the raw bytes, response.text is that body decoded with the detected encoding, response.url is the final URL after any redirects, and response.history lists the redirect responses along the way.

ExceptionWhen it happens
ConnectionErrorDNS failure, refused connection, network down
Timeout (ConnectTimeout, ReadTimeout)no connection or no data within the limit
HTTPErrorraise_for_status() saw a 4xx or 5xx
JSONDecodeErrorresponse.json() got a body that is not JSON
RequestExceptionthe base class of all of the above

Every one of these exceptions derives from requests.exceptions.RequestException, so the order of except clauses matters: catch the specific classes (HTTPError, Timeout) first and RequestException last. session.mount(prefix, adapter) chooses which transport adapter sends requests for a URL prefix. That is how you add retries with HTTPAdapter(max_retries=...) and how tests replace the network with a fake adapter.

Mental model: the session pipeline
  1. Session merges in default headers
  2. params are encoded into the URL
  3. The adapter for the prefix sends it
  4. raise_for_status() checks the status

Swap the adapter and you get retries or offline tests without touching the rest of the code.

General pattern

python
with requests.Session() as session:
    session.headers.update({"Header-Name": "value"})
    try:
        resp = session.get(url, params=query, timeout=(connect_s, read_s))
        resp.raise_for_status()
        data = resp.json()
    except requests.exceptions.HTTPError as e:
        handle_status(e.response.status_code)
    except requests.exceptions.RequestException as e:
        handle_network_problem(e)

Open the Session with with, set default headers once and give every request a timeout. Catch HTTPError first and every remaining network problem with RequestException last.

Example: a Session on top of a fake adapter

So the example runs offline, the FakeTransport adapter builds responses itself instead of using the network. The Session, the params encoding, the timeout handed to the adapter and raise_for_status() are all real requests code. The adapter prints each request it receives, so you can see what the Session added.

session_demo.py
import json

import requests
from requests.adapters import BaseAdapter


# --- Offline stand-in for the network: a transport adapter that answers itself ---
class FakeTransport(BaseAdapter):
    def send(self, request, **kwargs):
        print(f"-> {request.method} {request.url} timeout={kwargs['timeout']}")
        print(f"   Accept: {request.headers['Accept']}")
        resp = requests.Response()
        resp.request, resp.url = request, request.url
        if "/users/1" in request.url:
            resp.status_code, resp.reason = 200, "OK"
            resp._content = json.dumps({"id": 1, "name": "Aye"}).encode()
        elif "/users?" in request.url:
            resp.status_code, resp.reason = 200, "OK"
            resp._content = json.dumps([{"id": 7, "name": "Aye Mya"}]).encode()
        else:
            resp.status_code, resp.reason = 404, "Not Found"
            resp._content = b'{"error": "no such user"}'
        resp.headers["Content-Type"] = "application/json"
        return resp

    def close(self):
        pass


API = "https://api.example.com"
session = requests.Session()
session.headers.update({"Accept": "application/json"})
session.mount(API, FakeTransport())

r = session.get(f"{API}/users/1", timeout=5)
r.raise_for_status()
print("user:", r.json())

r = session.get(f"{API}/users", params={"q": "aye mya", "page": 2}, timeout=(3.05, 10))
print("search:", r.status_code, r.json())

try:
    r = session.get(f"{API}/users/42", timeout=5)
    r.raise_for_status()
except requests.exceptions.HTTPError as e:
    print("HTTPError:", e)

Code breakdown

  1. Default headersession.headers.update({"Accept": "application/json"})

    Written once, yet the output shows Accept: application/json on all three requests.

  2. Mountsession.mount(API, FakeTransport())

    URLs starting with https://api.example.com go through FakeTransport. In production you would delete this line or mount an HTTPAdapter with retries instead.

  3. params + tuple timeoutr = session.get(f"{API}/users", params={"q": "aye mya", "page": 2}, timeout=(3.05, 10))

    The URL becomes ?q=aye+mya&page=2 and the adapter receives timeout=(3.05, 10). A real HTTPAdapter would allow 3.05 seconds to connect and 10 seconds to read.

  4. Adapter receives kwargsdef send(self, request, **kwargs):

    The Session hands the PreparedRequest to adapter.send() with keywords such as timeout, verify and proxies. It is a fake, but it implements the real adapter interface.

  5. HTTPError message r.raise_for_status() except requests.exceptions.HTTPError as e:

    The 404 raises HTTPError whose message carries the status, the reason and the URL. e.response gives you the whole response back.

You should see
-> GET https://api.example.com/users/1 timeout=5
   Accept: application/json
user: {'id': 1, 'name': 'Aye'}
-> GET https://api.example.com/users?q=aye+mya&page=2 timeout=(3.05, 10)
   Accept: application/json
search: 200 [{'id': 7, 'name': 'Aye Mya'}]
-> GET https://api.example.com/users/42 timeout=5
   Accept: application/json
HTTPError: 404 Client Error: Not Found for url: https://api.example.com/users/42
Requests Library Visual Guide
Fetching API data with requests.get() and reading the JSON response, as a diagram.

Adding retries with HTTPAdapter

requests does not retry on its own, but you can mount an HTTPAdapter that carries a urllib3 Retry object. backoff_factor makes the pause between attempts grow, and status_forcelist lists the statuses worth retrying. Limiting allowed_methods to GET and HEAD keeps a POST from being sent twice by accident. This snippet only configures the adapter; it sends no request.

retry_session.py
import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry

retry = Retry(total=3, backoff_factor=0.5,
              status_forcelist=[429, 500, 502, 503, 504],
              allowed_methods=["GET", "HEAD"])   # never blindly retry POST
session = requests.Session()
session.mount("https://", HTTPAdapter(max_retries=retry))

adapter = session.get_adapter("https://api.example.com/items")
print(type(adapter).__name__, adapter.max_retries.total)

In real projects

Where this shows up in real projects

Services that call third-party APIs usually create one Session in a module or a client class and reuse it everywhere. That Session holds the User-Agent, the Authorization header, an adapter with retries and the default timeout in one place, so every request automatically follows the same policy. Sync jobs that fetch hundreds of pages often see their runtime drop noticeably just from connection reuse.

Responses should not be trusted blindly either. Production code checks that Content-Type really is application/json and that Content-Length is within what it is willing to accept, and downloads large files in chunks with stream=True and iter_content(). In tests, a fake adapter like the one in this lesson, or a library such as responses, replaces the network so the tests stay fast and stable.

Common mistakes

Common mistakes

1. Silencing certificate errors with verify=False

The error disappears, but so does any proof that you are talking to the real server, so tokens and data can be stolen. For an internal CA, point verify at the CA bundle path, and check the system clock and the certificate's expiry.

2. Treating timeout=5 as a total limit

The read timeout is the wait between bytes, so a server that trickles data slowly can keep one request going far longer than five seconds. If you need an overall deadline, use stream=True and measure the elapsed time yourself.

3. Catching only HTTPError

With only except HTTPError, DNS failures, refused connections and timeouts slip through and crash the program. Catch RequestException after HTTPError, but avoid a bare Exception, which would also hide bugs in your own code.

4. Retrying POST without thinking

If the server created the order and the timeout happened on the way back, resending the POST creates a second order. Use an idempotency key if the API supports one; otherwise retry only safe methods such as GET automatically.

Best practices

Best practices

  • Create one Session per API and keep its base URL, headers and default timeout together in a client class.
  • Put your app's name and version in the User-Agent header, which makes problems easier to trace on the provider's side.
  • Limit retries to safe methods such as GET and to temporary statuses such as 429 and 5xx, with backoff.
  • Never hit the real network in tests; control responses with an adapter or a mock.

Mini challenge

Mini challenge: a defensive get_json()

Write get_json(), which takes a Session and a URL and returns either the JSON data or a clear error string. To avoid the network, also complete a FakeTransport adapter that serves the responses in ROUTES.

  • FakeTransport.send() builds a requests.Response from the status, Content-Type and body in ROUTES, and raises ReadTimeout for /slow
  • get_json() sends with timeout=(3.05, 10) and calls raise_for_status()
  • Return "error: timed out" on a timeout and "error: HTTP <code>" on an HTTPError
  • If Content-Type is not application/json, return an error string instead of calling .json()
get_json.py
import requests
from requests.adapters import BaseAdapter

ROUTES = {  # path -> (status, content type, body)
    "/status": (200, "application/json", b'{"healthy": true}'),
    "/login": (200, "text/html", b"<html>Please sign in</html>"),
    "/report": (500, "application/json", b'{"error": "db down"}'),
}


class FakeTransport(BaseAdapter):
    def send(self, request, **kwargs):
        # TODO: for request.path_url == "/slow", raise requests.exceptions.ReadTimeout
        # TODO: otherwise build a requests.Response from ROUTES and return it
        ...

    def close(self):
        pass


def get_json(session, url):
    # TODO: GET with timeout=(3.05, 10), then raise_for_status()
    # TODO: turn Timeout / HTTPError into "error: ..." strings
    # TODO: refuse bodies whose Content-Type is not application/json
    ...


# TODO: mount FakeTransport on a Session and call get_json for
#       /status, /login, /report and /slow

Expected: Output for the four paths: /status -> {'healthy': True} /login -> error: expected JSON, got text/html /report -> error: HTTP 500 /slow -> error: timed out

Show hint

For a fake response, setting status_code, url, reason, headers["Content-Type"] and _content (bytes) is enough. ReadTimeout is a subclass of Timeout, so except requests.exceptions.Timeout catches it.

Show solution
get_json.py
import requests
from requests.adapters import BaseAdapter

ROUTES = {  # path -> (status, content type, body)
    "/status": (200, "application/json", b'{"healthy": true}'),
    "/login": (200, "text/html", b"<html>Please sign in</html>"),
    "/report": (500, "application/json", b'{"error": "db down"}'),
}


class FakeTransport(BaseAdapter):
    def send(self, request, **kwargs):
        path = request.path_url
        if path == "/slow":
            raise requests.exceptions.ReadTimeout("read timed out", request=request)
        status, ctype, body = ROUTES[path]
        resp = requests.Response()
        resp.status_code, resp.url, resp._content = status, request.url, body
        resp.reason = "OK" if status == 200 else "Internal Server Error"
        resp.headers["Content-Type"] = ctype
        return resp

    def close(self):
        pass


def get_json(session, url):
    try:
        response = session.get(url, timeout=(3.05, 10))
        response.raise_for_status()
    except requests.exceptions.Timeout:
        return "error: timed out"
    except requests.exceptions.HTTPError as e:
        return f"error: HTTP {e.response.status_code}"
    content_type = response.headers.get("Content-Type", "")
    if not content_type.startswith("application/json"):
        return f"error: expected JSON, got {content_type}"
    return response.json()


session = requests.Session()
session.mount("https://api.example.com", FakeTransport())
for path in ["/status", "/login", "/report", "/slow"]:
    print(path, "->", get_json(session, "https://api.example.com" + path))

Quick quiz 1 / 3

In session.get(url, timeout=(3.05, 10)), what does the tuple mean?

Quick quiz 2 / 3

Which single except clause catches a ReadTimeout, a ConnectionError and an HTTPError from raise_for_status()?

Quick quiz 3 / 3

Which URL does session.get("https://api.example.com/users", params={"q": "aye mya", "page": 2}) request?

What to remember

  • Use a Session for many requests: it reuses headers, cookies and connections.
  • Build query strings with params= and give every request a timeout or a (connect, read) tuple.
  • Catch HTTPError first and RequestException last, and never use verify=False.
  • Swap adapters with session.mount() to add retries or to test without a network.

Requests — User Guide — Requests

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Requests Library | Thuta Learning