TExcelTAD

Calling REST APIs

Most automation ends up talking to an HTTP API: a cloud provider, GitHub, a monitoring system, an internal service catalogue. A good API client in a script does the same few things every time: build URLs with properly encoded query strings, send an auth header, decode JSON, turn HTTP errors into exceptions with useful messages, and set a timeout. This lesson builds such a client in a way that can be tested without a network.

Design: the client does not know how bytes travel

The client below never opens a socket itself. It builds a Request, hands it to a transport (any function that takes a Request and returns a Response), and interprets the answer. In production the transport is a thin wrapper around urllib or requests; in tests, and in this browser where there is no network, it is a fake API that lives in the same program. Swapping one for the other is a one-line change.

python · try it yourself
import json
from dataclasses import dataclass, field
from urllib.parse import urlencode

@dataclass
class Request:
    method: str
    url: str
    headers: dict = field(default_factory=dict)
    body: bytes | None = None

@dataclass
class Response:
    status: int
    headers: dict
    body: bytes
    def json(self):
        return json.loads(self.body) if self.body else None

class ApiError(Exception):
    def __init__(self, status, method, url, detail):
        super().__init__(f"{method} {url} -> HTTP {status}: {detail}")
        self.status = status

class ServiceCatalog:
    """A client for a small service-catalogue API."""
    def __init__(self, base_url, token, transport):
        self.base_url = base_url.rstrip("/")
        self.token = token
        self.transport = transport

    def _call(self, method, path, params=None, body=None):
        url = self.base_url + path + ("?" + urlencode(params) if params else "")
        headers = {"Authorization": f"Bearer {self.token}", "Accept": "application/json",
                   "User-Agent": "catalog-script/1.0"}
        data = None
        if body is not None:
            data = json.dumps(body).encode()
            headers["Content-Type"] = "application/json"
        resp = self.transport(Request(method, url, headers, data))
        if not 200 <= resp.status < 300:
            detail = (resp.json() or {}).get("error", "") if resp.body else ""
            raise ApiError(resp.status, method, url, detail)
        return resp.json()

    def list_services(self, team=None):
        return self._call("GET", "/v1/services", {"team": team} if team else None)["items"]

    def get_service(self, name):
        return self._call("GET", f"/v1/services/{name}")

    def scale(self, name, replicas):
        return self._call("PATCH", f"/v1/services/{name}", body={"replicas": replicas})

# ---- an in-process fake of the API, standing in for the real server ----
class FakeCatalogApi:
    def __init__(self):
        self.services = {
            "shop-api": {"name": "shop-api", "team": "core", "replicas": 2},
            "search":   {"name": "search",   "team": "find", "replicas": 3},
            "worker":   {"name": "worker",   "team": "core", "replicas": 1},
        }
        self.log = []

    def __call__(self, req: Request) -> Response:
        self.log.append(f"{req.method} {req.url}")
        if req.headers.get("Authorization") != "Bearer s3cret":
            return self._json(401, {"error": "invalid token"})
        path, _, query = req.url.removeprefix("https://catalog.example.com").partition("?")
        parts = path.strip("/").split("/")                  # ["v1", "services", name?]
        if parts[:2] != ["v1", "services"]:
            return self._json(404, {"error": "no such endpoint"})
        if len(parts) == 2 and req.method == "GET":
            team = dict(p.split("=") for p in query.split("&") if p).get("team")
            items = [s for s in self.services.values() if team in (None, s["team"])]
            return self._json(200, {"items": items})
        svc = self.services.get(parts[2])
        if svc is None:
            return self._json(404, {"error": f"service {parts[2]} not found"})
        if req.method == "GET":
            return self._json(200, svc)
        if req.method == "PATCH":
            svc.update(json.loads(req.body))
            return self._json(200, svc)
        return self._json(405, {"error": "method not allowed"})

    @staticmethod
    def _json(status, obj):
        return Response(status, {"Content-Type": "application/json"}, json.dumps(obj).encode())

api = FakeCatalogApi()
catalog = ServiceCatalog("https://catalog.example.com", "s3cret", transport=api)

print([s["name"] for s in catalog.list_services()])
print([s["name"] for s in catalog.list_services(team="core")])
print(catalog.scale("worker", 4))

for name, client in [("unknown", catalog),
                     ("shop-api", ServiceCatalog("https://catalog.example.com", "wrong", transport=api))]:
    try:
        client.get_service(name)
    except ApiError as e:
        print("ApiError:", e)

print("requests sent:")
for line in api.log:
    print("  " + line)
['shop-api', 'search', 'worker']
['shop-api', 'worker']
{'name': 'worker', 'team': 'core', 'replicas': 4}
ApiError: GET https://catalog.example.com/v1/services/unknown -> HTTP 404: service unknown not found
ApiError: GET https://catalog.example.com/v1/services/shop-api -> HTTP 401: invalid token
requests sent:
  GET https://catalog.example.com/v1/services
  GET https://catalog.example.com/v1/services?team=core
  PATCH https://catalog.example.com/v1/services/worker
  GET https://catalog.example.com/v1/services/unknown
  GET https://catalog.example.com/v1/services/shop-api

What the client gets right:

  • Query strings are encoded with urlencode, never by string concatenation (team=a&b would break the URL).
  • Every request carries the same headers: auth, Accept, and a User-Agent that names your script, so API owners can find it in their logs.
  • HTTP errors become exceptions that include the method, URL, status and the API's own error message. A script that ignores a 401 and carries on with an empty list is a script that reports "0 services down" when it is actually locked out.
  • The token is not hard-coded. In a real script it comes from an environment variable or a secret store, and it never appears in log lines (note that api.log records URLs, not headers).

The real transport

Here are two transports for the real network. Both take the same Request and return the same Response, so the client above works unchanged. They do not run in the browser sandbox (no network), so they are shown as plain code:

python
import os
import urllib.error
import urllib.request

def urllib_transport(req: Request, timeout: float = 10.0) -> Response:
    """Standard library only: good for scripts copied to servers."""
    r = urllib.request.Request(req.url, data=req.body, headers=req.headers, method=req.method)
    try:
        with urllib.request.urlopen(r, timeout=timeout) as resp:
            return Response(resp.status, dict(resp.headers), resp.read())
    except urllib.error.HTTPError as e:              # 4xx/5xx raise in urllib; turn them back into responses
        return Response(e.code, dict(e.headers), e.read())

catalog = ServiceCatalog("https://catalog.example.com", os.environ["CATALOG_TOKEN"], transport=urllib_transport)
python
import requests

session = requests.Session()                         # reuses connections between calls

def requests_transport(req: Request, timeout: float = 10.0) -> Response:
    resp = session.request(req.method, req.url, headers=req.headers, data=req.body, timeout=timeout)
    return Response(resp.status_code, dict(resp.headers), resp.content)

Notes on the real thing:

  • Always pass a timeout. Neither urllib nor requests has a useful default: without one, a server that accepts the connection and never answers hangs your script forever.
  • urllib raises HTTPError for 4xx/5xx, requests does not (unless you call raise_for_status()); the transport hides that difference, which is another benefit of the design.
  • Connection failures (urllib.error.URLError, requests.ConnectionError) are not HTTP responses; let them propagate, or handle them in the retry layer of the next lesson.
  • TLS verification is on by default in both. Never turn it off to "fix" a certificate error; fix the trust store (REQUESTS_CA_BUNDLE, SSL_CERT_FILE) instead.

Testing with the fake

The fake API is not only a workaround for the sandbox: it is how you test API code. A test builds the fake in a known state, runs the code under test, and checks both the result and the requests that were sent:

python · try it yourself
def scale_down_idle(get_json, patch_json, services):
    """Scale services with zero traffic to 1 replica. Returns the names it changed."""
    changed = []
    for name in services:
        svc = get_json(f"/v1/services/{name}")
        if svc["requests_per_min"] == 0 and svc["replicas"] > 1:
            patch_json(f"/v1/services/{name}", {"replicas": 1})
            changed.append(name)
    return changed

# The fake records every PATCH so the test can assert on it
state = {"api": {"replicas": 3, "requests_per_min": 120}, "batch": {"replicas": 4, "requests_per_min": 0},
         "cron": {"replicas": 1, "requests_per_min": 0}}
patches = []
get_json = lambda path: state[path.rsplit("/", 1)[1]]
def patch_json(path, body):
    patches.append((path, body))
    state[path.rsplit("/", 1)[1]].update(body)

changed = scale_down_idle(get_json, patch_json, ["api", "batch", "cron"])
assert changed == ["batch"], changed
assert patches == [("/v1/services/batch", {"replicas": 1})], patches
assert state["batch"]["replicas"] == 1
print("all assertions passed; changed:", changed)
all assertions passed; changed: ['batch']

The logic under test takes two small functions instead of a whole client, the same idea at a smaller scale: depend on the narrowest interface you need, and the test needs no network, no mocking library and no running server.

Test yourself

Why does the ServiceCatalog client take a transport argument?

  1. Python requires it for HTTP
  2. So the same client can use a real HTTP library in production and an in-process fake in tests or offline sandboxes
  3. To make requests faster
  4. To encrypt the token

What happens with urllib.request.urlopen(url) and no timeout when the server accepts the connection but never replies?

  1. It fails after 10 seconds
  2. It can wait forever
  3. It retries automatically
  4. It returns an empty response

Why should an API client raise an exception on HTTP 401 instead of returning an empty list?

  1. Exceptions are faster
  2. Otherwise a script that is locked out looks like it found nothing, and reports success
  3. 401 is not a real status code
  4. Empty lists cannot be printed