Home β€Ί Curriculum β€Ί Consuming APIs with requests
Updated for Python 3.12+ Β· November 2026

πŸ”Œ Consuming APIs with requests
in Python

Learn the Python requests library for APIs: GET, POST, params, headers, JSON, timeouts, sessions, auth, retries and pagination, with runnable mock examples.

Intermediate 10 lessonsβ‰ˆ 65 min read by Glenn Pansensoy

What this lesson is about

Almost every interesting program eventually needs to talk to another program over the network: fetch the weather, post a message to a chat channel, read a list of repositories, charge a card, or pull rows from a company's internal service. Most of those conversations happen over HTTP, and in Python the friendliest tool for the job is the third-party requests library. You describe the request in a line or two of Python, and you get back an object with the status code, the headers and the body already decoded.

Calling an API looks easy in a tutorial and then goes wrong in production. The server is slow, so your script hangs forever. It returns a 429 because you asked too often. It returns an HTML error page when your code expected JSON. A list of results arrives in pages and you only processed the first one. Real API code is mostly about handling those cases calmly, and that is what I want you to learn here, not just the happy path.

I have organised this lesson as a ladder. We start with what an HTTP exchange actually contains, then the first GET, query parameters, POST with JSON, timeouts and errors, sessions, authentication, retries and pagination, and finally how to test all of it. The requests package cannot run inside a web page, so the real code is marked static and you run it on your own computer. Next to each one I have written a runnable teaching version that uses a small fake response class and unittest.mock, so you can experiment with the logic right here and see the same output every time.

What you will learn

  • βœ“What a request and a response contain: method, URL, headers, status code and body
  • βœ“How to send GET requests with query parameters and read JSON safely
  • βœ“How to send POST requests with json= and data= and why they differ
  • βœ“How to set timeouts and handle Timeout, ConnectionError and HTTPError
  • βœ“How a Session reuses connections and shares headers, cookies and auth
  • βœ“How basic auth, bearer tokens and API keys are really sent
  • βœ“How to retry with exponential backoff and respect Retry-After
  • βœ“How to walk paginated results and test your client without the network

Why programmers should learn this

  • β˜…Nearly every modern service, from payment providers to weather feeds to your own company's backend, exposes an HTTP API, so this skill unlocks automation, data collection and integrations.
  • β˜…Knowing timeouts, retries and status checks is what separates a script that works on your laptop from a job that keeps running overnight when the network misbehaves.
  • β˜…Understanding what requests sends on the wire makes API documentation and error messages much easier to read, because every doc is really describing methods, headers and bodies.
  • β˜…Writing a client you can test with fakes means your tests are fast, free and deterministic, and they never hit a real service or burn through a rate limit.
  • β˜…The same ideas carry straight into other tools such as httpx, aiohttp, JavaScript's fetch and command line curl, so the time you spend here is not tied to one library.

What an API call really contains

An HTTP exchange is two blocks of text. Your program sends a request: a method such as GET or POST, a path, a set of headers, and sometimes a body. The server answers with a response: a status line with a three digit code, a set of headers, and usually a body. Everything requests does is a convenient way to write the first block and read the second. When something goes wrong, thinking in these terms is the fastest way to find the bug.

The status code tells you the outcome in broad strokes. Codes starting with 2 mean success (200 OK, 201 Created, 204 No Content). Codes starting with 3 are redirects. Codes starting with 4 mean you made a mistake: 400 bad request, 401 not authenticated, 403 not allowed, 404 not found, 429 too many requests. Codes starting with 5 mean the server failed, and these are often temporary. That 4xx versus 5xx split matters a great deal later, because you should usually retry a 503 but never retry a 400.

Headers are key and value pairs that describe the message. Content-Type says how to read the body, Authorization carries credentials, Accept says what format you would like back, and Retry-After tells you how long to wait. Header names are case insensitive. To make this concrete, the block below takes a raw response as text, exactly as it travels over the network, and pulls it apart by hand. You will see that there is no magic in it.

Pulling a raw HTTP response apart
import json

raw_response = (
    "HTTP/1.1 200 OK\r\n"
    "Content-Type: application/json; charset=utf-8\r\n"
    "X-RateLimit-Remaining: 58\r\n"
    "\r\n"
    '{"login": "octocat", "public_repos": 8}'
)

head, _, body = raw_response.partition("\r\n\r\n")
status_line, *header_lines = head.split("\r\n")
version, code, reason = status_line.split(" ", 2)

headers = {}
for line in header_lines:
    name, _, value = line.partition(":")
    headers[name.strip().lower()] = value.strip()

print("status:", int(code), reason)
print("content type:", headers["content-type"])
print("remaining:", int(headers["x-ratelimit-remaining"]))

data = json.loads(body)
print("login:", data["login"], "| repos:", data["public_repos"])
Expected output
status: 200 OK
content type: application/json; charset=utf-8
remaining: 58
login: octocat | repos: 8

Line by line

  1. 3-9A response is plain text: a status line, header lines, a blank line, then the body. Here it is built from a few string pieces joined by \r\n.
  2. 11The first blank line (\r\n\r\n) separates the head from the body, so partition splits there.
  3. 12-13The first line of the head is the status line; the rest are header lines. Split the status line into protocol version, code and reason phrase.
  4. 15-18Turn each Name: value line into a dictionary entry. Lower-casing the name makes lookups case insensitive, like real HTTP headers.
  5. 20-22Print the numeric status, the content type and the rate limit header converted to an int.
  6. 24-25The body is just text, so json.loads turns it into a dictionary you can index.

This is exactly what a requests.Response object gives you, already organised: resp.status_code, resp.reason, resp.headers and resp.json(). Install the library first, ideally inside a virtual environment, then we will make a real call.

Your first GET and reading the response

A GET request asks the server for a resource and should never change anything on the server. With requests it is one function call. The two attributes you will use constantly are resp.status_code and resp.json(). Use resp.text when the body is plain text or HTML, and resp.content when you need the raw bytes, for example for an image.

Notice the timeout=10 argument in the real example. By default requests waits forever, and a script that waits forever is a script that never finishes. I will say more about this later, but make it a habit from your very first call: always pass a timeout. Also notice that a 404 does not raise an exception by itself. The call succeeded in the sense that a server answered, so you have to look at the status yourself or call resp.raise_for_status().

Because the real library needs a network, I want you to be able to practise the logic without it. The runnable block below defines a small FakeResponse class with the same attributes as the real thing, then uses unittest.mock.patch.object to swap the get function for one that returns a prepared fake. This is the technique professionals use to test API code, and it gives the same output on every run. Read the mock call details at the end: they show you exactly how your function called the library.

Install requestsrun on your computer
python -m pip install requests

Line by line

  1. 1Install the library into the active environment. Use a virtual environment so the version is isolated per project.
A real GET requestrun on your computer
import requests

resp = requests.get(
    "https://api.example.com/users/octocat",
    headers={"Accept": "application/json"},
    timeout=10,
)

print(resp.status_code)
print(resp.headers["Content-Type"])
data = resp.json()
print(data["login"])

Line by line

  1. 1Import the library.
  2. 3-7Send a GET. headers adds an Accept header, and timeout=10 gives up after ten seconds instead of waiting forever.
  3. 9-10Print the numeric status and a response header; header lookup is case insensitive.
  4. 11-12Decode the JSON body into a normal Python dictionary and read one key.
Faking requests.get with FakeResponse and mock
import json
import types
from unittest import mock

class HTTPError(Exception):
    pass

class FakeResponse:
    """A tiny stand-in for requests.Response."""
    def __init__(self, status_code=200, payload=None, headers=None):
        self.status_code = status_code
        self.text = json.dumps(payload)
        self.headers = headers or {}

    @property
    def ok(self):
        return self.status_code < 400

    def json(self):
        return json.loads(self.text)

    def raise_for_status(self):
        if not self.ok:
            raise HTTPError(f"{self.status_code} error")

# a stand-in for the real module, so this runs without a network
requests = types.SimpleNamespace(get=None)

def get_repo_count(username):
    resp = requests.get(f"https://api.example.com/users/{username}", timeout=5)
    resp.raise_for_status()
    return resp.json()["public_repos"]

good = FakeResponse(200, {"public_repos": 8})
with mock.patch.object(requests, "get", return_value=good) as fake_get:
    print("repos:", get_repo_count("octocat"))
    print("called with:", fake_get.call_args)

missing = FakeResponse(404, {"message": "Not Found"})
with mock.patch.object(requests, "get", return_value=missing):
    try:
        get_repo_count("ghost")
    except HTTPError as err:
        print("caught:", err)
Expected output
repos: 8
called with: call('https://api.example.com/users/octocat', timeout=5)
caught: 404 error

Line by line

  1. 1-3Standard library imports: json to encode the fake body, types for a simple namespace, and unittest.mock for patching.
  2. 5-6A stand-in for requests.HTTPError, so we can raise something realistic.
  3. 8-14FakeResponse stores a status code, a text body and headers, just like the real class.
  4. 16-22ok is true below 400, and json() decodes the stored text. Real requests behaves the same way.
  5. 24-26raise_for_status raises for any 4xx or 5xx code and does nothing otherwise.
  6. 28-29A fake requests module with one attribute, get, which tests will replace.
  7. 31-34The function under test: call the API, check the status, return one field.
  8. 36-39patch.object temporarily replaces requests.get with a mock that returns our fake. Inside the with block the function never touches a network, and call_args records how it was called.
  9. 41-46Same idea for a 404: the function should raise, and we catch the error to prove it.

In a real project you would write mock.patch("myapp.client.requests.get") against the module that imports requests. The rule is to patch the name where it is looked up, not where it is defined.

Query parameters and building URLs

Most GET endpoints accept options in the query string, the part of the URL after the question mark, such as ?q=python&per_page=20. You could glue this together with string formatting, but you would immediately meet quoting problems: spaces, ampersands, accents and non-ASCII characters all need percent encoding. The right way is to hand requests a dictionary through params= and let it encode everything correctly.

A list value becomes a repeated key, so {"tag": ["a", "b"]} is sent as tag=a&tag=b, which is how many APIs expect multiple values. A value of None is dropped, which is handy for optional filters: you can build one dictionary with every possible filter and leave the unused ones as None. After the call, resp.url shows the final URL that was actually requested, which is the best debugging tool you have when results look wrong.

The standard library has the same machinery in urllib.parse, and since it works in any Python, I can show you the idea in the runnable block below. urlencode turns a dictionary into a query string, and parse_qs reverses it. If you ever wonder why a plus sign or %20 appears in a URL, this is where it comes from.

How params become a query string
from urllib.parse import urlencode, urlsplit, parse_qs

params = {"q": "python web apis", "per_page": 2, "tag": ["http", "json"]}
query = urlencode(params, doseq=True)
print(query)

url = "https://api.example.com/search?" + query
parts = urlsplit(url)
print("path :", parts.path)
print("query:", parse_qs(parts.query))

optional = {"q": "cats", "lang": None, "page": 3}
clean = {k: v for k, v in optional.items() if v is not None}
print(urlencode(clean))
Expected output
q=python+web+apis&per_page=2&tag=http&tag=json
path : /search
query: {'q': ['python web apis'], 'per_page': ['2'], 'tag': ['http', 'json']}
q=cats&page=3

Line by line

  1. 1urlencode builds query strings; urlsplit and parse_qs take them apart again.
  2. 3-5A dictionary of options, including a list value. doseq=True repeats the key for each list item, and the space in the text becomes a plus sign.
  3. 7-10Attach the query to a URL, split the URL into parts, and parse the query back into a dictionary of lists.
  4. 12-14requests skips parameters whose value is None. This dictionary comprehension does the same, so you can see the effect.
Params, status checks and resp.url (real requests)run on your computer
import requests

resp = requests.get(
    "https://api.example.com/search",
    params={"q": "python web apis", "per_page": 2, "tag": ["http", "json"]},
    timeout=10,
)
print(resp.url)
resp.raise_for_status()
for item in resp.json()["items"]:
    print(item["name"])

try:
    bad = requests.get("https://api.example.com/missing", timeout=10)
    bad.raise_for_status()
except requests.HTTPError as err:
    print("failed:", err.response.status_code)

Line by line

  1. 3-7Pass a dictionary as params; requests encodes it and appends it to the URL.
  2. 8resp.url shows the exact URL that was sent, which is invaluable when debugging.
  3. 9-11Raise on 4xx and 5xx, then loop through the items in the decoded JSON.
  4. 13-17raise_for_status raises requests.HTTPError. The error carries the response, so you can read err.response.status_code.

POST, JSON bodies and headers

A POST request sends data to the server, usually to create something. The body can be encoded in different ways, and requests has a separate argument for each. Use json= when the API expects JSON: the library serialises your dictionary and sets Content-Type: application/json for you. Use data= with a dictionary for classic HTML form encoding (application/x-www-form-urlencoded). Passing a dictionary to data= when the API wants JSON is one of the most common mistakes, and the server often answers with a confusing 400 or 415.

Headers customise the request. Common ones are Accept (what format you want), Authorization (credentials), User-Agent (who you are; some APIs ask you to set a descriptive one) and custom ones like X-Request-ID. Pass them as a dictionary. Anything you set yourself wins over the library's default, so you can override even Content-Type when you must.

Different success codes carry different meanings. A create usually answers 201 Created, often with a Location header pointing to the new resource and the created object in the body. A delete often answers 204 No Content, which has an empty body, so calling resp.json() on it would fail. Always check the status before you decode. The runnable block builds a request description the way requests does, so you can compare what json= and data= actually put on the wire.

json= versus data= on the wire
import json
from urllib.parse import urlencode

def build_request(method, url, params=None, headers=None, json_body=None, data=None):
    sent = {"User-Agent": "demo-client/1.0", "Accept": "*/*"}
    sent.update(headers or {})
    body = None
    if params:
        url += ("&" if "?" in url else "?") + urlencode(params, doseq=True)
    if json_body is not None:
        body = json.dumps(json_body)
        sent.setdefault("Content-Type", "application/json")
    elif data is not None:
        body = urlencode(data)
        sent.setdefault("Content-Type", "application/x-www-form-urlencoded")
    return method.upper(), url, sent, body

for label, kwargs in [
    ("json=", dict(json_body={"title": "Buy milk", "done": False})),
    ("data=", dict(data={"title": "Buy milk", "done": False})),
]:
    method, url, sent, body = build_request(
        "post", "https://api.example.com/todos", headers={"X-Request-ID": "abc123"}, **kwargs
    )
    print(label, method, url)
    print("  Content-Type:", sent["Content-Type"])
    print("  X-Request-ID:", sent["X-Request-ID"])
    print("  body:", body)
Expected output
json= POST https://api.example.com/todos
  Content-Type: application/json
  X-Request-ID: abc123
  body: {"title": "Buy milk", "done": false}
data= POST https://api.example.com/todos
  Content-Type: application/x-www-form-urlencoded
  X-Request-ID: abc123
  body: title=Buy+milk&done=False

Line by line

  1. 4-5A small function that mimics how a client prepares a request: start with default headers, then let the caller's headers override them.
  2. 7-9Query parameters are appended to the URL, using & if a query already exists.
  3. 10-12With a JSON body the dictionary is serialised and Content-Type defaults to JSON.
  4. 13-15With form data the dictionary is URL encoded instead, and the content type changes to match.
  5. 16Return the pieces so we can inspect them.
  6. 18-21Run the same payload through both paths.
  7. 22-27Print the method, URL, the content type and the body. Notice that the JSON body has quotes and braces while the form body is key=value pairs.
POST with json= and data= (real requests)run on your computer
import requests

resp = requests.post(
    "https://api.example.com/items",
    json={"name": "notebook", "qty": 3},
    headers={"X-Request-ID": "abc123"},
    timeout=10,
)
print(resp.status_code)
print(resp.headers.get("Location"))
print(resp.json())

form = requests.post(
    "https://api.example.com/form",
    data={"username": "glenn", "remember": "1"},
    timeout=10,
)
print(form.status_code)

gone = requests.delete("https://api.example.com/items/1", timeout=10)
if gone.status_code == 204:
    print("deleted, no body to decode")

Line by line

  1. 3-8json= serialises the dictionary and sets the JSON content type. We add one custom header.
  2. 9-11A create normally answers 201; the Location header, if present, points at the new resource. Use .get because a header may be absent.
  3. 13-18data= sends classic form fields instead.
  4. 20-22A delete often returns 204 with an empty body, so check the status instead of calling .json().
⚠️

Never put secrets such as passwords or tokens in a URL query string. URLs are stored in server logs and browser history. Send credentials in headers or in the request body.

Timeouts and error handling

Networks fail in several different ways, and requests gives each a different exception, all inheriting from requests.RequestException. A ConnectTimeout or ReadTimeout (both are requests.Timeout) means the server was too slow. A requests.ConnectionError means it could not connect at all: DNS failure, refused connection, no network. A requests.HTTPError is only raised when you call raise_for_status() on a 4xx or 5xx response. And a ValueError (specifically requests.JSONDecodeError) comes from resp.json() when the body is not valid JSON, which happens whenever a proxy or error page answers instead of the API.

The timeout argument can be a single number, applied to both connecting and reading, or a tuple (connect, read). Note what the read timeout means: it is the maximum time between bytes arriving, not a limit on the total download. A slow trickle can still run for a long time. For hard limits on total time, wrap the work in your own deadline logic, or use a library with a total timeout option.

My preferred pattern is a small function that makes one call and translates every failure into a result the rest of the program understands. That way the messy details stay in one place. The runnable block below simulates five scripted outcomes with stand-in exception classes that mirror the real hierarchy, so you can see the decision logic. In the static block after it I show the same structure with the real exceptions, ordered from most specific to most general.

Classifying failures (simulation)
import json

class RequestException(Exception): pass
class Timeout(RequestException): pass
class ConnectionError_(RequestException): pass
class HTTPError(RequestException): pass

class FakeResponse:
    def __init__(self, status, body):
        self.status_code, self.text = status, body
    def raise_for_status(self):
        if self.status_code >= 400:
            raise HTTPError(f"HTTP {self.status_code}")
    def json(self):
        return json.loads(self.text)

def scripted_call(step):
    if step == "slow":
        raise Timeout("read timed out")
    if step == "offline":
        raise ConnectionError_("name resolution failed")
    if step == "missing":
        return FakeResponse(404, '{"message": "no such user"}')
    if step == "html":
        return FakeResponse(200, "<html>Maintenance</html>")
    return FakeResponse(200, '{"name": "Ada"}')

def fetch(step):
    try:
        resp = scripted_call(step)
        resp.raise_for_status()
        return {"ok": True, "data": resp.json()}
    except Timeout:
        return {"ok": False, "why": "timeout, try again later"}
    except ConnectionError_:
        return {"ok": False, "why": "cannot reach the server"}
    except HTTPError as err:
        return {"ok": False, "why": f"server said {err}"}
    except ValueError:
        return {"ok": False, "why": "reply was not JSON"}

for step in ["fine", "slow", "offline", "missing", "html"]:
    print(f"{step:8}", fetch(step))
Expected output
fine     {'ok': True, 'data': {'name': 'Ada'}}
slow     {'ok': False, 'why': 'timeout, try again later'}
offline  {'ok': False, 'why': 'cannot reach the server'}
missing  {'ok': False, 'why': 'server said HTTP 404'}
html     {'ok': False, 'why': 'reply was not JSON'}

Line by line

  1. 3-6Stand-in exceptions with the same family tree as the real ones: everything inherits from one base class.
  2. 8-15A minimal fake response that raises on error codes and decodes JSON on request.
  3. 17-26A scripted fake of the network: each keyword triggers one failure mode, including an HTML page returned with a 200 status.
  4. 28-41The function to study. Make the call, check the status, decode, and translate each exception into a plain result dictionary. Order matters: catch specific exceptions before general ones.
  5. 43-44Run all five scenarios. The HTML page raises ValueError from json.loads, which the last handler catches.
Timeouts and exceptions (real requests)run on your computer
import requests

def fetch_json(url):
    try:
        resp = requests.get(url, timeout=(3.05, 10))
        resp.raise_for_status()
        return resp.json()
    except requests.Timeout:
        print("too slow, try again later")
    except requests.ConnectionError:
        print("could not connect")
    except requests.HTTPError as err:
        print("bad status:", err.response.status_code)
    except requests.JSONDecodeError:
        print("body was not valid JSON")
    except requests.RequestException as err:
        print("something else went wrong:", err)
    return None

print(fetch_json("https://api.example.com/users/octocat"))

Line by line

  1. 5A tuple timeout: up to 3.05 seconds to connect and 10 seconds waiting for data between bytes.
  2. 6-7Check for HTTP errors, then decode the body.
  3. 8-17Catch the specific exceptions first and the general RequestException last. requests.JSONDecodeError covers an invalid body.
  4. 18Return None when anything failed, so the caller can test for it.
  5. 20Call the function with a URL; on success it prints the decoded dictionary.
πŸ’‘

Wrap every network call in a function like this and return something simple. The rest of your program then deals in data and clear errors, not in library exceptions.

Sessions: reuse connections and share defaults

Calling requests.get repeatedly opens a fresh connection each time, with a new TCP handshake and TLS negotiation on every call. A requests.Session keeps connections alive and reuses them, which makes many calls to the same host noticeably faster. It also remembers state: headers you set on the session go out with every request, cookies the server sets are sent back automatically, and you can set one auth value for all calls.

Use a session as a context manager so connections are closed properly, with requests.Session() as s:. Per-request arguments are merged with the session's defaults, and the per-request value wins. One important gotcha: a Session has no default timeout, and there is no setting to give it one. A common fix is to subclass it and apply a default in request, as in the static example below.

To see why this design is handy, the runnable block builds a miniature FakeSession that merges default headers with per-call headers, stores cookies from a response and counts how many connections it needed. Real requests is far more capable, but the mental model is the same: a session is a bundle of defaults plus a connection pool.

A miniature session
class FakeSession:
    def __init__(self):
        self.headers = {"User-Agent": "demo/1.0"}
        self.cookies = {}
        self.open_hosts = set()
        self.connections_opened = 0
        self.log = []

    def request(self, method, url, headers=None):
        host = url.split("/")[2]
        if host not in self.open_hosts:
            self.open_hosts.add(host)
            self.connections_opened += 1
        sent = {**self.headers, **(headers or {})}
        if self.cookies:
            sent["Cookie"] = "; ".join(f"{k}={v}" for k, v in sorted(self.cookies.items()))
        self.log.append((method, url, sent))
        if url.endswith("/login"):
            self.cookies["session_id"] = "s-42"
        return sent

s = FakeSession()
s.headers["Accept"] = "application/json"
s.request("GET", "https://api.example.com/login")
s.request("GET", "https://api.example.com/profile", headers={"Accept": "text/plain"})
s.request("GET", "https://api.example.com/orders")

for method, url, sent in s.log:
    print(method, url.split("example.com")[1], "|", sent.get("Accept"), "|", sent.get("Cookie"))
print("connections opened:", s.connections_opened)
Expected output
GET /login | application/json | None
GET /profile | text/plain | session_id=s-42
GET /orders | application/json | session_id=s-42
connections opened: 1

Line by line

  1. 1-7The session holds default headers, a cookie jar, a set of hosts with an open connection, a counter and a log.
  2. 10-14Work out the host from the URL. Only the first request to a host needs a new connection; later ones reuse it.
  3. 15Merge session headers with per-call headers; the second dictionary wins on a clash.
  4. 16-18If cookies exist, build a Cookie header from them, sorted so the output is stable. Then record the request.
  5. 19-20The login response sets a cookie, like a real server would.
  6. 23-27Create the session, set a default header, then make three calls. The second overrides Accept.
  7. 29-31Print what each call sent and how many connections were needed. The cookie appears only after login, and one connection serves all three requests.
A real Session with a default timeoutrun on your computer
import requests

class TimeoutSession(requests.Session):
    def __init__(self, timeout=10):
        super().__init__()
        self.default_timeout = timeout

    def request(self, method, url, **kwargs):
        kwargs.setdefault("timeout", self.default_timeout)
        return super().request(method, url, **kwargs)

with TimeoutSession(timeout=5) as session:
    session.headers.update({"Accept": "application/json", "User-Agent": "poetic-bytes-demo/1.0"})
    first = session.get("https://api.example.com/users/octocat")
    second = session.get("https://api.example.com/search", params={"q": "python"})
    print(first.status_code, second.status_code)
    print(session.cookies.get_dict())

Line by line

  1. 3-6Subclass Session and remember a default timeout.
  2. 8-10Every call funnels through request. setdefault adds the timeout only when the caller did not pass one.
  3. 12Use the session as a context manager so its connection pool closes cleanly.
  4. 13Headers set here are sent with every request made through the session.
  5. 14-16Two calls reuse the same connection; per-call params are merged in.
  6. 17Cookies set by the server are stored on the session; get_dict() shows them.

Authentication: basic, bearer and API keys

Most real APIs need to know who you are. The three schemes you will meet most often are all simple once you see what goes over the wire. Basic auth joins username:password, encodes it with base64 and sends Authorization: Basic <encoded>. Bearer tokens send Authorization: Bearer <token>, and are used by OAuth based APIs and most modern services. API keys are sent in a header such as X-API-Key, or occasionally as a query parameter. Read the provider's documentation to see which one they use and which header name.

In requests, auth=(user, password) handles basic auth for you, and for the others you set the header yourself. Never hard code a secret in your source file. Read it from an environment variable, and keep local development values in a file that is excluded from version control. If a token ever appears in a repository, treat it as stolen and rotate it. Also remember that basic auth is only safe over HTTPS, because base64 is an encoding, not encryption.

The block below shows that base64 point in action, so you never confuse encoding with security. It encodes and decodes a basic auth header, and builds a bearer header from a token read from a fake environment dictionary. Notice how little is going on: authentication is just one more header.

What auth headers really look like
import base64

def basic_header(user, password):
    raw = f"{user}:{password}".encode("utf-8")
    return "Basic " + base64.b64encode(raw).decode("ascii")

def bearer_header(token):
    return f"Bearer {token}"

fake_env = {"API_TOKEN": "tok_live_example123"}

h1 = basic_header("glenn", "s3cret")
print(h1)

encoded = h1.split(" ", 1)[1]
print("anyone can decode it:", base64.b64decode(encoded).decode())

headers = {"Authorization": bearer_header(fake_env["API_TOKEN"])}
print(headers)

masked = headers["Authorization"][:12] + "..."
print("safe to log:", masked)
Expected output
Basic Z2xlbm46czNjcmV0
anyone can decode it: glenn:s3cret
{'Authorization': 'Bearer tok_live_example123'}
safe to log: Bearer tok_l...

Line by line

  1. 3-5Basic auth: join user and password with a colon, base64 encode the bytes, and prefix the word Basic.
  2. 7-8Bearer auth is just the word Bearer and the token.
  3. 10A dictionary standing in for os.environ; real code reads the token from the environment.
  4. 12-13Build and print a basic header.
  5. 15-16Decode it back to prove that base64 hides nothing. This is why basic auth needs HTTPS.
  6. 18-19Build the bearer header as a dictionary, ready to pass as headers=.
  7. 21-22When logging, mask all but the first few characters so secrets never reach log files.
Auth with real requestsrun on your computer
import os
import requests

token = os.environ["API_TOKEN"]

# bearer token in a header
resp = requests.get(
    "https://api.example.com/private",
    headers={"Authorization": f"Bearer {token}"},
    timeout=10,
)
print(resp.status_code)

# basic auth: requests builds the header for you
resp = requests.get(
    "https://api.example.com/private",
    auth=("glenn", os.environ["API_PASSWORD"]),
    timeout=10,
)

# API key in a custom header, set once on a session
with requests.Session() as session:
    session.headers["X-API-Key"] = os.environ["API_KEY"]
    print(session.get("https://api.example.com/private", timeout=10).status_code)

Line by line

  1. 4Read the secret from an environment variable; a KeyError here is a good early warning that setup is incomplete.
  2. 6-12Bearer token: build the Authorization header yourself.
  3. 14-19Basic auth: pass a (user, password) tuple and the library encodes it.
  4. 21-24An API key in a custom header, attached once to a session so every call includes it.
⚠️

A 401 means the server does not know who you are (missing or bad credentials). A 403 means it knows you but you are not allowed. Telling them apart saves a lot of debugging.

Retries and exponential backoff

Some failures are temporary: a 503 while a server restarts, a 429 because you went over a rate limit, a connection reset. Retrying is the right answer for those, but only if you do it politely. Hammering a struggling server in a tight loop makes things worse. The standard approach is exponential backoff: wait one second, then two, then four, with a cap. Adding a little random jitter stops thousands of clients from retrying at the very same instant.

Equally important is knowing what not to retry. A 400, 401, 403 or 404 will fail the same way every time, so retrying only wastes effort. Be careful with non-idempotent methods too. Retrying a POST that creates an order might create two orders if the first request actually succeeded but the response was lost. Retry GET, HEAD, PUT and DELETE freely; retry POST only when the API supports an idempotency key. If a response includes a Retry-After header, obey it: the server is telling you exactly how long to wait.

The runnable block implements the whole policy in about twenty lines, with an injected sleep function so it records the waits instead of really sleeping. The random generator is seeded so the output is the same each run. In real projects you rarely write this yourself: urllib3, which powers requests, ships a Retry class that you attach to a session through an adapter, as in the static example.

Backoff with jitter and Retry-After
import random

class FakeResponse:
    def __init__(self, status, headers=None):
        self.status_code = status
        self.headers = headers or {}

RETRYABLE = {429, 500, 502, 503, 504}

def get_with_retries(call, max_attempts=5, base=0.5, cap=8.0, sleep=None, rng=None):
    waits = []
    for attempt in range(1, max_attempts + 1):
        resp = call()
        if resp.status_code not in RETRYABLE:
            return resp, waits
        if attempt == max_attempts:
            break
        if "Retry-After" in resp.headers:
            delay = float(resp.headers["Retry-After"])
        else:
            delay = rng.uniform(0, min(cap, base * 2 ** attempt))
        waits.append(round(delay, 2))
        sleep(delay)
    return resp, waits

script = iter([
    FakeResponse(503),
    FakeResponse(429, {"Retry-After": "3"}),
    FakeResponse(502),
    FakeResponse(200),
])
slept = []
resp, waits = get_with_retries(lambda: next(script), sleep=slept.append, rng=random.Random(7))
print("final status:", resp.status_code)
print("waits:", waits)
print("total waited:", round(sum(slept), 2))

resp, waits = get_with_retries(lambda: FakeResponse(404), sleep=slept.append, rng=random.Random(7))
print("404 retried?", bool(waits))
Expected output
final status: 200
waits: [0.32, 3.0, 0.6]
total waited: 3.93
404 retried? False

Line by line

  1. 3-6A tiny fake response with a status and headers.
  2. 8Only these statuses are worth retrying: rate limiting and server side failures.
  3. 10-12The retry helper takes the call to make, limits, and injected sleep and random generator so it is easy to test.
  4. 13-16Make the call. If the status is not retryable, return immediately, even for errors like 404.
  5. 17-18Stop after the last attempt instead of sleeping for nothing.
  6. 19-23Prefer the server's Retry-After value. Otherwise use full jitter: a random delay between zero and an exponentially growing ceiling that is capped.
  7. 24-26Record the delay, then wait. Here sleep just appends to a list.
  8. 28-33A scripted sequence of responses: 503, 429 with a three second hint, 502, then success.
  9. 34-39Run it and print the final status, the delays chosen and their total. The seeded generator makes them repeatable.
  10. 41-42A 404 is returned at once, with no waiting.
Retry adapter for a real Sessionrun on your computer
import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry

retry = Retry(
    total=4,
    backoff_factor=0.5,
    status_forcelist=[429, 500, 502, 503, 504],
    allowed_methods=["GET", "HEAD", "OPTIONS"],
    respect_retry_after_header=True,
)
adapter = HTTPAdapter(max_retries=retry)

session = requests.Session()
for prefix in ("https://", "http://"):
    session.mount(prefix, adapter)

resp = session.get("https://api.example.com/flaky", timeout=10)
print(resp.status_code)

Line by line

  1. 5-11Describe the policy: up to four retries, a growing delay controlled by backoff_factor, retry only on these statuses, only for safe methods, and honour Retry-After.
  2. 12Wrap the policy in an adapter, the object that actually sends requests for a session.
  3. 14-16Mount the adapter for both URL prefixes so every request through the session follows the policy.
  4. 18-19Calls now retry automatically. If all attempts fail on a status in the list, requests raises RetryError, so catch requests.RequestException as before.

Pagination: getting every result

APIs rarely return everything at once. A list of ten thousand items is split into pages, and you must keep asking until you have them all. There are three common styles. Page number pagination uses ?page=2&per_page=50. Offset and limit uses ?offset=100&limit=50. Cursor pagination returns an opaque token like next_cursor that you pass back, which stays correct even when data changes while you read. Some APIs also send a Link header with a rel="next" URL, and requests parses it into resp.links.

The Python tool that fits all of these is a generator. A function that yields each item hides the paging loop from the caller, who simply writes for item in all_items(): .... Because generators are lazy, the next page is fetched only when needed, so you can stop early without downloading everything. Always keep a safety valve such as a maximum page count, so a buggy server that never stops returning a next link cannot trap you in an endless loop.

I wrote two runnable examples. The first pages through a fake API using a page number and stops when a page comes back short. The second follows Link headers, parsing them with a regular expression. Both use a fake fetch function in place of the network, so you can see the generator logic on its own.

Paging with a generator
import re

ITEMS = [f"item-{n}" for n in range(1, 8)]

def fake_fetch_page(page, per_page):
    start = (page - 1) * per_page
    return {"items": ITEMS[start:start + per_page], "page": page}

def all_items(per_page=3, max_pages=50):
    for page in range(1, max_pages + 1):
        data = fake_fetch_page(page, per_page)
        yield from data["items"]
        if len(data["items"]) < per_page:
            return

print(list(all_items()))

# Link header style
def fake_fetch_link(url):
    page = int(url.rsplit("=", 1)[1])
    body = ITEMS[(page - 1) * 3: page * 3]
    link = ""
    if page * 3 < len(ITEMS):
        link = f'<https://api.example.com/items?page={page + 1}>; rel="next"'
    return body, link

def parse_next(link_header):
    match = re.search(r'<([^>]+)>;\s*rel="next"', link_header)
    return match.group(1) if match else None

def follow_links(first_url):
    url = first_url
    while url:
        body, link = fake_fetch_link(url)
        yield from body
        url = parse_next(link)

print(list(follow_links("https://api.example.com/items?page=1")))
first_two = []
for item in follow_links("https://api.example.com/items?page=1"):
    first_two.append(item)
    if len(first_two) == 2:
        break
print(first_two)
Expected output
['item-1', 'item-2', 'item-3', 'item-4', 'item-5', 'item-6', 'item-7']
['item-1', 'item-2', 'item-3', 'item-4', 'item-5', 'item-6', 'item-7']
['item-1', 'item-2']

Line by line

  1. 3Seven fake records. With three per page we get pages of 3, 3 and 1.
  2. 5-7A fake API call that slices the list by page number.
  3. 9-14The generator asks for page 1, 2, 3... and yield from hands each item to the caller. A short page means we reached the end. max_pages is the safety valve.
  4. 16Collect every item into a list to show the loop hid the paging.
  5. 19-25A second fake API that returns a body plus a Link header pointing at the next page, and no link on the last one.
  6. 27-29Extract the rel="next" URL from a header with a regular expression, or return None.
  7. 31-36Follow links until none remain, yielding items as we go.
  8. 38-44Because generators are lazy, breaking out of the loop after two items stops further page fetches.
Pagination with real requestsrun on your computer
import requests

def iter_items(session, url, params=None, max_pages=100):
    pages = 0
    while url and pages < max_pages:
        resp = session.get(url, params=params, timeout=10)
        resp.raise_for_status()
        yield from resp.json()["items"]
        url = resp.links.get("next", {}).get("url")
        params = None          # the next url already contains the query
        pages += 1

with requests.Session() as session:
    names = [item["name"] for item in iter_items(session, "https://api.example.com/items", {"per_page": 50})]
    print(len(names), "items")

Line by line

  1. 3-4A generator that takes a session, a start URL and optional first-page params, and counts pages as a safety valve.
  2. 5-8Fetch a page, fail loudly on errors, and yield each item.
  3. 9resp.links is a dictionary parsed from the Link header; take the next URL, or None when absent.
  4. 10Clear params after the first request, because the next URL already includes its own query string.
  5. 13-15Consume the generator with a list comprehension and report how many items arrived.

Testing your client and putting it together

A good API client is a small class that owns the base URL, the session, the timeout and the error translation, and exposes methods named after what your program wants, such as get_user or create_todo. The rest of your code never builds URLs or inspects status codes. This keeps the dirty details in one file and makes the code far easier to test.

There are two practical ways to test it. The first is mocking, as we have done in this lesson: replace the session with a fake that returns prepared responses, then assert on the result and on the calls made. This is fast and needs nothing installed. The second is to start a real server on your own machine, on a random free port, and point the client at it. Python's http.server plus a thread is enough, and it checks that the real requests code really works over a real socket, including headers and JSON bodies. I recommend both: mocks for the logic, one or two local server tests for the wiring.

The runnable block builds an ApiClient that takes a session as an argument (dependency injection), and tests it with a fake session. The static block shows a self contained local server test using only the standard library and requests, which you can run on your own computer. A third option is the third party responses or requests-mock packages, which patch requests for you with a friendlier interface; they are worth knowing once your test suite grows.

A client you can test without a network
import json

class ApiError(Exception):
    pass

class FakeResponse:
    def __init__(self, status, payload):
        self.status_code = status
        self._payload = payload
    def json(self):
        return self._payload

class FakeSession:
    def __init__(self, responses):
        self.responses = list(responses)
        self.calls = []
    def request(self, method, url, **kwargs):
        self.calls.append((method, url, kwargs))
        return self.responses.pop(0)

class ApiClient:
    def __init__(self, base_url, session, timeout=10):
        self.base_url = base_url.rstrip("/")
        self.session = session
        self.timeout = timeout

    def _call(self, method, path, **kwargs):
        resp = self.session.request(method, self.base_url + path, timeout=self.timeout, **kwargs)
        if resp.status_code >= 400:
            raise ApiError(f"{method} {path} failed with {resp.status_code}")
        return resp.json()

    def get_todo(self, todo_id):
        return self._call("GET", f"/todos/{todo_id}")

    def create_todo(self, title):
        return self._call("POST", "/todos", json={"title": title})

session = FakeSession([
    FakeResponse(200, {"id": 1, "title": "Write lesson"}),
    FakeResponse(201, {"id": 2, "title": "Test client"}),
    FakeResponse(404, {"message": "not found"}),
])
client = ApiClient("https://api.example.com/", session)

print(client.get_todo(1))
print(client.create_todo("Test client"))
try:
    client.get_todo(99)
except ApiError as err:
    print("ApiError:", err)

for method, url, kwargs in session.calls:
    print(method, url, sorted(kwargs))
Expected output
{'id': 1, 'title': 'Write lesson'}
{'id': 2, 'title': 'Test client'}
ApiError: GET /todos/99 failed with 404
GET https://api.example.com/todos/1 ['timeout']
POST https://api.example.com/todos ['json', 'timeout']
GET https://api.example.com/todos/99 ['timeout']

Line by line

  1. 3-4One error type for the whole client, so callers need only one except.
  2. 6-11A fake response with a status and a payload.
  3. 13-19A fake session that hands out prepared responses in order and records every call.
  4. 21-35The client: it stores the base URL and timeout, and a single _call method adds the timeout, checks the status and decodes JSON.
  5. 37-41Public methods read like the domain: get a todo, create a todo.
  6. 43-48Script three responses (success, created, not found) and build the client with the fake session.
  7. 50-56Exercise the client; the third call should raise ApiError.
  8. 58-59Inspect the recorded calls to confirm every request carried a timeout, and that the POST carried a JSON body.
Test against a real local serverrun on your computer
import json
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

import requests

class Handler(BaseHTTPRequestHandler):
    def _send(self, status, payload):
        body = json.dumps(payload).encode()
        self.send_response(status)
        self.send_header("Content-Type", "application/json")
        self.send_header("Content-Length", str(len(body)))
        self.end_headers()
        self.wfile.write(body)

    def do_GET(self):
        if self.path == "/todos/1":
            self._send(200, {"id": 1, "title": "Write lesson"})
        else:
            self._send(404, {"message": "not found"})

    def do_POST(self):
        length = int(self.headers.get("Content-Length", 0))
        data = json.loads(self.rfile.read(length))
        self._send(201, {"id": 2, **data})

    def log_message(self, *args):
        pass  # keep test output quiet

server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
base = f"http://127.0.0.1:{server.server_port}"
threading.Thread(target=server.serve_forever, daemon=True).start()

try:
    print(requests.get(f"{base}/todos/1", timeout=5).json())
    created = requests.post(f"{base}/todos", json={"title": "Test client"}, timeout=5)
    print(created.status_code, created.json())
    print(requests.get(f"{base}/todos/99", timeout=5).status_code)
finally:
    server.shutdown()

Line by line

  1. 1-5Standard library pieces for a tiny server plus requests as the client under test.
  2. 7-14A handler base: a helper that sends a JSON response with the correct headers and length.
  3. 16-20GET returns a todo for one known path and a 404 for everything else.
  4. 22-25POST reads exactly Content-Length bytes of the request body, decodes the JSON and echoes it back with an id and a 201 status.
  5. 27-28Silence the default per-request logging.
  6. 30-32Port 0 asks the operating system for any free port. Start the server in a background daemon thread.
  7. 34-40Call it with real requests code, then shut the server down in finally so the thread ends.
πŸ’‘

Mock to test your logic quickly, and use a local server for one or two tests that prove the real library, real headers and real JSON all fit together.

Common mistakes

❌ Forgetting the timeout

requests waits forever by default, so one unresponsive server can freeze your whole program. Pass timeout= on every call, or use a session subclass that applies a default.

❌ Assuming a 404 or 500 raises an exception

A response with an error status is still a successful network call. Either test resp.ok and the status code yourself or call resp.raise_for_status() right after the request.

❌ Using data= when the API expects JSON

data= sends form encoding. If the API documentation shows a JSON body, use json= so the content type and the encoding both match.

❌ Retrying everything

Retrying a 400, 401 or 404 never helps, and retrying a non-idempotent POST can create duplicates. Retry temporary failures (429 and 5xx) on safe methods, with backoff.

❌ Hard coding secrets

A token pasted into source code ends up in version control. Read secrets from environment variables, mask them in logs, and rotate any that leak.

Quick quiz

Tap an answer. I explain every one, right or wrong.

Q1. What does resp.raise_for_status() do?

Q2. You want the API to receive a JSON body. Which argument should you use?

Q3. What does timeout=(3, 10) mean?

Q4. Why use a Session for many calls to one host?

Q5. Which status should you normally retry with backoff?

Q6. Why is base64 in basic auth not a security feature?

Frequently asked questions

No. It is a third-party package that you install with pip. The standard library has urllib.request and http.client, which work but are more verbose. Many projects also use httpx, which has a very similar API and adds async support.

Not directly: calls block the thread. For concurrent requests in async programs use httpx or aiohttp, or run requests in a thread pool. The ideas in this lesson (timeouts, retries, pagination, testing) apply to them as well.

Use files={"file": open(path, "rb")} to upload multipart data. To download without loading everything into memory, pass stream=True and read the body in pieces with resp.iter_content(chunk_size=8192), ideally inside a with block so the connection is released.

The body was not valid JSON. Common causes are an HTML error or login page, an empty body (for example after a 204), or a server returning plain text. Check the status code and resp.headers.get("Content-Type") before decoding.

Not automatically. Read the provider's terms of use and rate limits, identify your client with a sensible User-Agent where requested, and keep your request rate polite. Official documentation tells you what is allowed.

Key takeaways

  • βœ“An HTTP exchange is a request (method, URL, headers, body) and a response (status, headers, body); requests just makes both easy to handle.
  • βœ“Always pass a timeout, and decide explicitly how to treat 4xx and 5xx responses with raise_for_status().
  • βœ“Use params= for query strings, json= for JSON bodies and data= for form bodies.
  • βœ“A Session reuses connections and shares headers, cookies and auth; retries and backoff belong on the session.
  • βœ“Retry only temporary failures on safe methods, honour Retry-After, and hide paging behind a generator.
  • βœ“Wrap the API in a small client class, test the logic with fakes and mocks, and verify the wiring with a local server.