APIs

Chapter 12 ยท Python Programming

API Fundamentals

12.1 ยท GET, Params, and Error Handling

Today's goals

  • Explain what a web API is and read an API contract
  • Choose an HTTP method and read a status code
  • Make a GET request and parse its JSON body
  • Build query parameters safely
  • Handle HTTP errors, timeouts, and invalid JSON

A request and a response

A Python program sends a request with a method, URL, query parameters, and headers to a web API; the API sends back a response with a status code, headers, and a JSON body

  • An API is a defined way for one program to ask another for a service
  • A web API exposes it through URLs; REST treats each URL as a resource

HTTP methods

Method Purpose Typical success Safe Idempotent
GET Retrieve one resource or a list 200 OK Yes Yes
POST Create a resource or submit data 201 Created No No
PUT Create or replace a whole resource 200, 204, or 201 No Yes
PATCH Change part of a resource 200 or 204 No Not guaranteed
DELETE Remove a resource 204 No Content No Yes
  • Safe: does not ask to change server state
  • Idempotent: same intended effect whether sent once or several times

A request times out, and you cannot tell whether the server received it. Which is safest to send again?

  1. POST /orders with a new order
  2. DELETE /saved-cities/42
  3. PATCH /accounts/7 with {"visits": "+1"}
  4. POST /payments with a charge

Status codes

Code range Meaning Typical action
2xx Success Parse the response
3xx Redirect Usually handled by the client library
4xx Client-side problem Check the endpoint, parameters, or authentication; for 429 Too Many Requests, wait and retry
5xx Server-side problem Retry later or report failure gracefully

Describe every API call as endpoint + method + parameters + expected response shape.

Read an API contract: Open-Meteo

Field Value
Endpoint https://api.open-meteo.com/v1/forecast
Method GET
Required params latitude, longitude
Optional param used here current_weather=true
Response latitude, longitude, and a nested current_weather

Live demo: check the contract

endpoint = "https://api.open-meteo.com/v1/forecast"
expected_keys = ["latitude", "longitude", "current_weather"]
response = requests.get(
    endpoint,
    params={"latitude": 37.95, "longitude": -91.77, "current_weather": "true"},
    timeout=10,
)
live = response.json()
print("Contract keys present:", all(key in live for key in expected_keys))
print("Current temperature:", live["current_weather"]["temperature"])
Contract keys present: True
Current temperature: 1.6

Live demo: get() is a shortcut for request()

url, params = "https://httpbin.org/get", {"q": "python"}
r1 = requests.get(url, params=params, timeout=10)
r2 = requests.request("GET", url, params=params, timeout=10)
print("r1:", r1.request.method, r1.url, r1.status_code)
print("Server saw the same query:", r1.json()["args"] == r2.json()["args"])
r1: GET https://httpbin.org/get?q=python 200
Server saw the same query: True

GET requests without the network

class DemoResponse:
    def __init__(self, payload, status_code=200):
        self._payload, self.status_code = payload, status_code
    def raise_for_status(self):
        if self.status_code >= 400:
            raise requests.HTTPError(f"HTTP {self.status_code}")
    def json(self):
        return self._payload
  • Same two methods as a real requests.Response, so the parsing code is identical

JSON text and Python objects

Function Converts
json.loads(text) JSON string to Python
json.dumps(obj) Python to JSON string
JSON Python
true, false True, False
null None
raw = '{"raining": false, "alerts": null}'
weather = json.loads(raw)
print(weather["raining"], weather["alerts"])
print(json.dumps(weather))
False None
{"raining": false, "alerts": null}

What does json.dumps({"ok": False, "note": None}) print?

  1. {'ok': False, 'note': None}
  2. {"ok": false, "note": null}
  3. {"ok": "False", "note": "None"}
  4. An error: None cannot become JSON

Query parameters: let requests build the URL

params = {"city": "New York", "units": "fahrenheit"}
request = requests.Request("GET", "https://api.example.test/weather",
                           params=params).prepare()
print(request.url)
https://api.example.test/weather?city=New+York&units=fahrenheit
  • A prepared request shows the final URL without sending it

URL encoding

search = {"q": "fish & chips", "filter": "price=low"}
naive = "&".join(f"{k}={v}" for k, v in search.items())
print(naive)
print(urlencode(search))
print(quote("fish & chips"))
q=fish & chips&filter=price=low
q=fish+%26+chips&filter=price%3Dlow
fish%20%26%20chips
  • & and = become %26 and %3D, so a value cannot split the query string

Error handling: three ways a call can fail

  1. Network errors: timeout, DNS failure, broken connection; no response arrives
  2. HTTP errors: the server responds with 404, 500, ...
  3. Invalid JSON: the body is not JSON, such as an HTML maintenance page
def parse_json_response(response):
    try:
        response.raise_for_status()
        return response.json()
    except requests.HTTPError as error:
        print("HTTP error:", error)
    except ValueError as error:
        print("Invalid JSON:", error)
    return None

Three responses, no crash

print(parse_json_response(DemoResponse({"results": ["a", "b"]})))
print(parse_json_response(DemoResponse({}, status_code=404)))
print(parse_json_response(TextResponse("<html>Down for maintenance</html>")))
{'results': ['a', 'b']}
HTTP error: HTTP 404
None
Invalid JSON: Expecting value: line 1 column 1 (char 0)
None

Catching any request failure

Exception Raised when
requests.ConnectionError The server cannot be reached
requests.Timeout No reply within timeout
requests.HTTPError raise_for_status() sees 4xx or 5xx
  • All inherit from requests.RequestException
  • Catch a specific subclass first; catch the base class last

except requests.RequestException comes first, then except requests.Timeout. A timeout happens. Which block runs?

  1. The Timeout block, because it is more specific
  2. The RequestException block
  3. Both blocks, in order
  4. Neither: Python raises an error

Your turn: name the failure

Complete describe_failure(call_fn):

  1. Call call_fn() and return "ok" when nothing is raised
  2. Return "timeout" for requests.Timeout and "http error" for requests.HTTPError
  3. Return "other request error" for any other requests.RequestException

Recap

  • A call is endpoint + method + parameters + expected response shape
  • Safe methods only read; idempotent methods are safe to repeat
  • response.json() turns JSON text into dicts and lists; json.dumps() goes back
  • Use params= and let requests encode the URL
  • Use a timeout, raise_for_status(), and catch specific errors before RequestException

API Reliability

12.2 ยท Production Patterns

Today's goals

  • Send a POST with a JSON body
  • Put an API key in a header, read from an environment variable
  • Read nested JSON directly and defensively
  • Collect results across pages and cursors
  • Retry with exponential backoff, only when it is safe
  • Validate a response against its contract

POST requests

prepared = requests.Request(
    "POST", "https://api.example.test/users",
    json={"name": "Alice", "role": "student"},
).prepare()
print(prepared.method)
print(prepared.headers["Content-Type"])
print(prepared.body.decode())
POST
application/json
{"name": "Alice", "role": "student"}

Headers and API keys

def build_headers(token_env_var="DEMO_API_KEY"):
    token = os.environ.get(token_env_var)
    if token is None:
        token = "demo-token"   # real code: stop with a clear error
    return {"Authorization": f"Bearer {token}",
            "Accept": "application/json"}

print(build_headers()["Authorization"])
Bearer demo-token

Two key patterns, one rule

Pattern Header
Bearer token Authorization: Bearer <token>
Custom key header X-API-Key: <key>
  • The API's documentation names the header to use
  • Never hard-code a real key: anyone who can see the repository, including its history, can read it

Where should a private API key live?

  1. In the URL as ?key=..., so it is easy to see
  2. Hard-coded in the notebook, then removed before committing
  3. In an environment variable, read with os.environ.get()
  4. In a comment above the request

Nested JSON: direct and defensive

name = payload["user"]["profile"]["name"]
metrics = payload.get("metrics", [])
first_metric = metrics[0].get("value", 0) if metrics else 0
user = payload.get("user") or {}      # also covers "user": null
profile = user.get("profile") or {}
department = profile.get("department", "unknown")
print(name, first_metric, department)
Nia 42 Analytics
  • Index directly when the contract guarantees a field; use .get() when it is optional

Page-based pagination

def fetch_all_pages(get_page_fn, first_page=1):
    items, page = [], first_page
    while page is not None:
        payload = get_page_fn(page)
        items.extend(payload["items"])
        page = payload["next_page"]
    return items

print(fetch_all_pages(get_page))
['a', 'b', 'c', 'd', 'e']

Cursor-based pagination

cursor_pages = {
    "start": {"results": [101, 102], "next_cursor": "k7"},
    "k7": {"results": [103, 104], "next_cursor": "m2"},
    "m2": {"results": [105], "next_cursor": None},
}
  • Each response returns a token, next_cursor, to send with the next request
  • A missing or None cursor means the last page
  • Same loop: request, collect, follow the pointer, stop on None

A pagination loop never ends. What is the most likely bug?

  1. The loop never updates the page or cursor variable
  2. The loop uses extend instead of append
  3. The API returned too few items
  4. The first page number was 1 instead of 0

Retry with exponential backoff

def retry_call(call_fn, retries=3, base_delay=0.01):
    for attempt in range(1, retries + 1):
        try:
            return call_fn()
        except requests.Timeout:
            if attempt == retries:
                raise
            time.sleep(base_delay * (2 ** (attempt - 1)))

print(retry_call(FlakySource(failures_before_success=2).get, retries=4))
{'status': 'ok', 'calls': 3}

Retry on server errors

({'status': 200}, [0.001, 0.002])
({'status': 404}, [])
({'status': 503}, [0.001, 0.002, 0.004])
  • 503, 500: temporary server problems, so wait and retry
  • 404: a client problem, so do not retry; fix the request
  • After the last attempt, return the last response

Which requests are safe to retry

IDEMPOTENT_METHODS = {"GET", "PUT", "DELETE"}

def should_retry(method, status_code):
    return method.upper() in IDEMPOTENT_METHODS and status_code >= 500

for method, status in [("GET", 503), ("PUT", 500), ("POST", 503), ("GET", 404)]:
    print(f"{method} {status}: retry={should_retry(method, status)}")
GET 503: retry=True
PUT 500: retry=True
POST 503: retry=False
GET 404: retry=False

A POST /payments times out. Should your client retry it automatically?

  1. Yes: timeouts are transient, so always retry
  2. No, unless the API supports an Idempotency-Key header
  3. Yes, but only once
  4. No: a timeout means the payment failed

Validate the response contract

def parse_weather_response(payload):
    current = payload["current_weather"]
    missing = [k for k in ["temperature", "windspeed"] if k not in current]
    if missing:
        raise ValueError(f"Missing weather fields: {missing}")
    return {"temperature": current["temperature"], "windspeed": current["windspeed"]}

try:
    parse_weather_response({"current_weather": {"temperature": 21.4}})
except ValueError as error:
    print("Rejected:", error)
Rejected: Missing weather fields: ['windspeed']

Your turn: validate a user record

Write parse_user(payload):

  1. Check for the keys "id", "name", and "email"
  2. If any are missing, raise ValueError("Missing user fields: [...]"), in that order
  3. Otherwise return a new dict with only those three keys

Recap

  • json= sends a JSON body and sets Content-Type
  • Keys go in headers, read from environment variables, never in code
  • Index what the contract guarantees; .get() what is optional
  • Follow next_page or next_cursor until it is None
  • Retry with exponential backoff, and only idempotent requests that failed transiently
  • Validate at the boundary with a clear ValueError