Working with APIs & JSON
Every program so far has worked entirely with data typed directly into the source code, or read from a local file. Real software constantly needs data that lives somewhere else — a weather service, a payments provider, a social platform — and the standard way that data travels between two completely different programs, written in different languages, running on different machines, is a web API exchanging JSON. This chapter builds the exact mechanics: making a request, checking whether it worked, and turning the response into ordinary Python data structures the rest of a program already knows how to use.
How to read this chapter
- Sub-topics 1-2 are the entry point: what an API and JSON actually are, and the two core tools —
requests.get()for asking a server for data, andjson.loads()/json.dumps()for converting between a JSON string and Python data. - Sub-topic 3 is the shape of real responses: JSON almost never comes back flat — it's dicts nested inside lists nested inside dicts, and this is how to navigate that safely.
- Sub-topic 4 is what happens when things go wrong: a bad status code, a network failure, a key that isn't there — real API code has to expect all three.
- Sub-topics 5-6 round out real usage: sending query parameters and headers (the API-key pattern), plus one real, safe, keyless public API to try locally.
- Sub-topic 7 ties it together as one repeatable pipeline: request → parse → format — the shape every real API-consuming program follows, which the project builds on directly.
- No example in this chapter needs a live network connection. Every graded exercise, practice problem, challenge, and the project use a hardcoded JSON string standing in for "what the API would return," parsed with the exact same code that would handle a real response.
- Everything from Chapters 1-18 still applies — strings, dicts, lists, loops, functions, exceptions, file handling, classes, and regex, all of it.
requestsandjsonare the new ingredients.
requests) and the answer's shape (JSON).
1. What an API is, and why JSON
- An API is a defined way for one program to ask another program for data or to trigger an action.
- A web API exchanges data over the internet using HTTP — the same protocol a browser uses to load a page.
- JSON is the plain-text format almost every web API uses to shape its data, since it maps directly onto dicts and lists.
Python's requests library (installed separately from the
standard library, via pip install requests) is the
standard way to make a web request from Python code. This chapter
never actually calls a real server — every example simulates
what a response would look like with a hardcoded string standing in
for it, since a course with no backend can't depend on live internet
access being available to every learner every time.
{"name": "Ana",
"age": 30} is valid JSON and valid Python at the same time.
It became the standard data format for web APIs because nearly every
programming language can read and write it, making it a shared
language between programs that otherwise have nothing in common.
# In real code this would be:
# import requests
# response = requests.get("https://api.example.com/weather?city=Austin")
#
# This chapter simulates that response with a small class standing in for
# what requests.get() would actually return, so every example runs with
# no network access needed.
class FakeResponse:
"""Stands in for what requests.get() returns, for offline examples."""
def __init__(self, status_code, text):
self.status_code = status_code
self.text = text
def json(self):
import json
return json.loads(self.text)
response = FakeResponse(
status_code=200,
text='{"city": "Austin", "temp_f": 88, "condition": "Sunny"}',
)
print(response.status_code)
print(response.text)
print(response.json())
200
{"city": "Austin", "temp_f": 88, "condition": "Sunny"}
{'city': 'Austin', 'temp_f': 88, 'condition': 'Sunny'}
A real call to requests.get(url) returns a
Response object with exactly these same three things:
.status_code (a number reporting whether the request
succeeded), .text (the raw response body as one plain
string), and .json() (a method that parses that string
into Python dicts/lists automatically, only if the body actually is
JSON). FakeResponse above is a small stand-in built
specifically so this chapter's examples can use identical code
against a value that never touches the network.
.status_codeis a number:200means success,404means "not found,"500means the server itself had an error..textis the raw response, always a plain string, whether or not it happens to be valid JSON..json()parses.textinto real Python data — but only works if the body is actually valid JSON, otherwise it raises an error.
Go Deeper: why not just use XML, or a program's own custom text format?
XML predates JSON as a web data format and is still used in some older or enterprise systems, but it's considerably more verbose for the same data (opening and closing tags for everything) and doesn't map onto a language's native data structures nearly as directly as JSON maps onto dicts and lists. A fully custom format would require every API consumer to write its own one-off parser instead of reusing a standard library function — JSON won as the default specifically because "just about every language already has a built-in JSON parser" removes that entire category of work.
- An API is a defined way for one program to ask another for data; a web API does this over HTTP.
- JSON is the plain-text data format most web APIs use, since it maps directly onto dicts and lists.
- A response has a status code (2xx success, 4xx client error, 5xx server error), raw text, and (if the body is JSON) a parsed form.
2. json.loads() & json.dumps()
json.loads(text)parses a JSON string into Python data (dicts, lists, strings, numbers, booleans,None).json.dumps(data)does the reverse — converts Python data into a JSON string.json.dumps(data, indent=2)pretty-prints the result, which is far easier to read than one long unbroken line.
Response object's .json() method (Sub-topic 1) is really just calling json.loads() on .text automatically — understanding json.loads()/json.dumps() directly is what makes that automatic step stop feeling like magic.
Python's built-in json module (import json,
no separate install needed) is the standard-library tool for moving
between a JSON string and real Python data:
'{"a": 1}' (one plain string, no dict features at all)
into a real Python dict, {"a": 1}, that supports
indexing, .get(), looping, and everything else a dict
normally supports.
import json
json_text = '{"name": "Ana", "age": 30, "active": true}'
data = json.loads(json_text)
print(type(data))
print(data["name"])
print(data["age"] + 1)
back_to_text = json.dumps(data)
print(back_to_text)
print(type(back_to_text))
<class 'dict'>
Ana
31
{"name": "Ana", "age": 30, "active": true}
<class 'str'>
json.loads(json_text) turns the plain string into a real
Python dict — confirmed by type(data)
— which is why data["age"] + 1 works: it's a real
integer now, not text. json.dumps(data) reverses the
process, turning the dict back into a plain string. Notice one detail:
JSON's true became Python's True during
parsing, and would convert back to true again on the way
out — the json module handles that translation
automatically for booleans, null/None, and
numbers.
json.loads()takes a string, returns Python data (the "s" is for "string").json.dumps()takes Python data, returns a string (the "s" is for "string" here too — it's the reverse direction).- A one-line JSON string is fine for a computer to send over a network, but painful for a human to read — which is exactly what pretty-printing fixes.
Adding indent= to json.dumps() reformats the
same data across multiple lines with consistent spacing, which matters
constantly when debugging what an API actually sent back:
import json
data = {"city": "Austin", "temp_f": 88, "forecast": ["Sunny", "Clear"]}
compact = json.dumps(data)
pretty = json.dumps(data, indent=2)
print(compact)
print()
print(pretty)
{"city": "Austin", "temp_f": 88, "forecast": ["Sunny", "Clear"]}
{
"city": "Austin",
"temp_f": 88,
"forecast": [
"Sunny",
"Clear"
]
}
Both strings represent the exact same data — indent=2
only changes how it's displayed, spreading nested pieces
across their own lines with 2 spaces of indentation per level. This is
purely a readability tool for humans; a real program sending JSON over
a network almost always uses the compact form, since the extra
whitespace serves no purpose once nothing is going to visually inspect
it.
Go Deeper: json.load() and json.dump() (no "s") work directly with files
json.load(file_object) and json.dump(data,
file_object) — without the trailing "s" — do the
exact same job as loads()/dumps(), but
read from or write directly to an already-open file object (from
Chapter 13's with open(...) as f:) instead of a string
already sitting in memory. This chapter sticks to the string-based
loads()/dumps() versions since API
responses arrive as strings, not files, but the file versions are
worth knowing about for reading a local config.json or
similar.
json.loads(text)parses a JSON string into Python data;json.dumps(data)converts Python data back into a JSON string.- JSON's
true/false/nullmap to Python'sTrue/False/Noneautomatically in both directions. json.dumps(data, indent=2)pretty-prints the same data across multiple readable lines, purely for human inspection.
3. Navigating nested JSON
- Real API responses are almost never flat — they're dicts containing lists containing more dicts, several levels deep.
- Each level is navigated with the same tools already known:
[key]for a dict,[index]for a list. - A loop is usually needed once a list of several similar items shows up anywhere in the structure.
loads()/dumps() cleanly — real responses look much more like this sub-topic's example, and this is the actual skill of "reading" a real API response.
A response listing several days of forecast data is a realistic shape to practice on — a dict, containing a list, containing more dicts:
{
"city": "Austin",
"forecast": [
{"day": "Mon", "high_f": 88, "condition": "Sunny"},
{"day": "Tue", "high_f": 84, "condition": "Cloudy"},
{"day": "Wed", "high_f": 79, "condition": "Rain"}
]
}
[key]
or [index] lookup, one level at a time, same as any dict
or list already covered in Chapters 7-8.
import json
response_text = """
{
"city": "Austin",
"forecast": [
{"day": "Mon", "high_f": 88, "condition": "Sunny"},
{"day": "Tue", "high_f": 84, "condition": "Cloudy"},
{"day": "Wed", "high_f": 79, "condition": "Rain"}
]
}
"""
data = json.loads(response_text)
print(data["city"])
print(data["forecast"][0])
print(data["forecast"][0]["day"])
for day in data["forecast"]:
print(f"{day['day']}: {day['high_f']}F, {day['condition']}")
Austin
{'day': 'Mon', 'high_f': 88, 'condition': 'Sunny'}
Mon
Mon: 88F, Sunny
Tue: 84F, Cloudy
Wed: 79F, Rain
data["city"] is one dict lookup, same as always.
data["forecast"] is a list, so [0] reaches
its first item — which is itself a dict, so
["day"] reaches one more level in. The
for day in data["forecast"]: loop is the real payoff:
once a list of several similar records shows up (three days of
forecast here), looping over it is almost always simpler than
indexing each one by hand.
- Read the shape from the outside in: is the top level a dict or a list? What's inside each key/index?
- A pretty-printed sample (Sub-topic 2's
indent=2) makes the actual nesting visible, which is often the fastest way to figure out how to navigate an unfamiliar response. - Chain lookups one level at a time (
data["forecast"][0]["day"]) rather than trying to guess the whole path before writing any code.
Go Deeper: real APIs often nest much deeper than this
A production API response can easily be five or six levels deep,
with lists inside dicts inside lists. The technique never changes
as depth increases — only the number of chained
[key]/[index] lookups (or nested loops)
needed to reach a particular piece of data. When a structure gets
deep enough to be genuinely hard to read at a glance, pretty-printing
it once with json.dumps(data, indent=2) and reading
that output top to bottom is usually the fastest way to understand
it before writing any navigation code at all.
- Real JSON responses are typically nested: dicts containing lists containing more dicts.
- Each level is navigated with an ordinary
[key]or[index]lookup, chained one level at a time. - A loop is the natural tool once a list of several similar records appears anywhere in the structure.
4. Handling bad responses & missing keys
- A real request can fail in two different ways: the network call itself fails (
requests.exceptions.RequestException), or it succeeds but returns a non-2xx status code. dict.get(key, default)returns a fallback instead of raisingKeyErrorwhen a key genuinely might not be present.- Real API code checks for both failure modes before trusting the response contains what's expected.
The first failure mode is a status code that isn't in the 2xx success range — the request itself worked (a response came back at all), but it's reporting a problem rather than the expected data:
404 Not Found or
401 Unauthorized) means the request itself was somehow
invalid — a bad URL, missing credentials. A 5xx
status code (like 500 Internal Server Error) means the
request was fine, but the server broke while trying to handle it.
Either way, the response almost certainly does not contain
the JSON data a program was hoping for.
import json
class FakeResponse:
def __init__(self, status_code, text):
self.status_code = status_code
self.text = text
def json(self):
return json.loads(self.text)
def get_quote(response):
if response.status_code != 200:
print(f"Request failed with status {response.status_code}")
return None
return response.json()
good_response = FakeResponse(200, '{"quote": "Simplicity is the ultimate sophistication."}')
bad_response = FakeResponse(404, "Not Found")
print(get_quote(good_response))
print(get_quote(bad_response))
{'quote': 'Simplicity is the ultimate sophistication.'}
Request failed with status 404
None
get_quote() checks response.status_code
before ever calling .json() — if the request
didn't succeed, calling .json() on a 404 response's body
(which is often plain text like "Not Found", not valid
JSON at all) would raise its own separate error. Checking the status
first and returning early on failure means the rest of the function
never has to worry about a malformed body.
The second failure mode happens before any status code even exists:
the network call itself might fail outright — no internet
connection, a timeout, the server unreachable. Real
requests code wraps the call in a try/except
for exactly this:
requests.exceptions.RequestException?
RequestException is the base exception class the
requests library raises when a request fails at the
network level — no connection, a timeout, a broken URL —
before there's even a status code to check. Catching it is how real
code tells "the server responded, just with an error status" (Sub-topic
4's first half) apart from "the request never reached a server at
all."
# In real code:
#
# import requests
#
# try:
# response = requests.get("https://api.example.com/weather", timeout=5)
# response_ok = response.status_code == 200
# except requests.exceptions.RequestException as e:
# print(f"Network error: {e}")
# response_ok = False
# Simulated here with a function standing in for requests.get(), since a
# real network call can't run offline:
class NetworkError(Exception):
"""Stands in for requests.exceptions.RequestException in this offline demo."""
pass
def simulated_get(should_fail):
if should_fail:
raise NetworkError("Connection timed out")
return "response would go here"
try:
result = simulated_get(should_fail=True)
print(result)
except NetworkError as e:
print(f"Network error: {e}")
Network error: Connection timed out
The commented-out block at the top is the real, live pattern —
requests.get() wrapped in a try/except
requests.exceptions.RequestException. The runnable code below it
simulates the same shape with a custom NetworkError class
(Chapter 12's custom exceptions) standing in for the real one, so the
exact same try/except structure can be
demonstrated without any actual network access.
The third failure mode is more subtle: the request succeeds, the status is 200, the body really is valid JSON — but the JSON doesn't have a key the code expected. Chapter 8 already covered the dict methods involved; this is exactly where they matter:
data = {"city": "Austin", "temp_f": 88}
print(data.get("condition", "unknown"))
print(data.get("temp_f", 0))
try:
print(data["condition"])
except KeyError as e:
print(f"Missing key: {e}")
unknown
88
Missing key: 'condition'
data.get("condition", "unknown") returns the fallback
string "unknown" instead of crashing, since
"condition" genuinely isn't in this particular response
— a very real scenario, since not every API guarantees every
field is always present. data["condition"] with square
brackets, by contrast, raises KeyError the moment a key
is missing. The rule of thumb for real API code: use
.get() with a sensible default for any field that might
legitimately be absent, and reserve [key] only for fields
the API's documentation guarantees will always be there.
Go Deeper: raise_for_status() as a shortcut
Real requests responses have a convenience method,
response.raise_for_status(), which raises an
HTTPError automatically if the status code is 4xx or
5xx, and does nothing at all if it's a success code — letting
a single line replace an explicit
if response.status_code != 200: check in code that
prefers to handle all failures through one try/except
block instead of a separate if.
- A response can fail at the network level (caught with
try/except requests.exceptions.RequestException) or succeed but report a bad status code (checked withif response.status_code != 200:). dict.get(key, default)returns a fallback instead of raisingKeyErrorfor a key that might legitimately be missing from a response.- Real API code checks the network, the status code, and individual keys — trusting none of the three by default.
5. Query params & headers
params=sends extra key-value information as part of the URL, without hand-building the URL string.headers=sends extra metadata alongside the request — commonly used to pass an API key.- An API key belongs in an environment variable, never hardcoded directly in source code.
A query parameter is extra information appended to a URL after a
?, like ?city=Austin&units=imperial —
requests.get() can build that automatically from a plain
dict instead of it being typed by hand:
? (and joined
by & if there's more than one):
https://api.example.com/weather?city=Austin&units=imperial.
requests.get(url, params={"city": "Austin", "units": "imperial"})
builds that exact URL automatically from a plain dict, correctly
handling spaces and special characters that would otherwise need
manual escaping.
# In real code:
#
# import requests
# response = requests.get(
# "https://api.example.com/weather",
# params={"city": "Austin", "units": "imperial"},
# )
# print(response.url)
# --> https://api.example.com/weather?city=Austin&units=imperial
# What requests builds behind the scenes, shown directly:
base_url = "https://api.example.com/weather"
params = {"city": "Austin", "units": "imperial"}
query_string = "&".join(f"{key}={value}" for key, value in params.items())
full_url = f"{base_url}?{query_string}"
print(full_url)
https://api.example.com/weather?city=Austin&units=imperial
The commented block is the real, one-line way to do this with
requests — passing a plain dict as params=
instead of building the query string by hand. The runnable code below
it manually reconstructs what that dict turns into, using an
f-string-and-join() pattern from Chapter 9, purely to make
visible what params= is doing under the hood. Real
requests code should always use params=
directly rather than building URLs by hand — it also correctly
escapes spaces and special characters, which the simplified version
above does not.
Headers work similarly but travel separately from the URL — metadata about the request itself, most commonly used to prove who's making the request:
{"Authorization": f"Bearer {api_key}"} is one common
format), and read from an environment variable via
os.environ.get("API_KEY") — never hardcoded
directly into source code, since committing a real key to a public
repository exposes it to everyone.
import os
# In real code, this pulls a secret value from the environment instead of
# ever typing it directly in the source file:
api_key = os.environ.get("WEATHER_API_KEY", "")
if not api_key:
print("No API key found in the environment -- using a placeholder for this demo.")
api_key = "demo-placeholder-key"
headers = {"Authorization": f"Bearer {api_key}"}
print(headers)
# In real code:
# response = requests.get(url, headers=headers)
No API key found in the environment -- using a placeholder for this demo.
{'Authorization': 'Bearer demo-placeholder-key'}
os.environ.get("WEATHER_API_KEY", "") reads a value from
the operating system's environment variables — a place to store
configuration and secrets outside of source code entirely, so a real
key never appears in a file that could accidentally get committed to
a public repository. This example prints a placeholder fallback
message specifically because no real key is set here, which is
exactly the point: this chapter never handles a real key at all, only
the pattern for how one would be read safely if it existed.
- Query params (
params=) customize what is being requested — which city, which page, which sort order. - Headers (
headers=) carry metadata about the request — who's asking, what format is acceptable in response. - A real API key always comes from an environment variable, never a literal string typed into a source file.
Go Deeper: why does params= handle special characters better than manual string building?
A URL has its own set of reserved characters (spaces, &,
#, and others) that need to be "percent-encoded"
(a space becomes %20, for instance) to safely appear
inside one. Manually building a query string with an f-string, as
the demo above did purely to show the mechanism, skips that encoding
entirely — which breaks the moment a value contains a space or
special character. requests.get(url, params=params)
handles that encoding automatically and correctly, which is the real
reason to always prefer it over building query strings by hand in
actual production code.
params=passed torequests.get()builds a query string automatically from a plain dict.headers=sends metadata alongside a request, most commonly used for authentication via an API key.- API keys always come from environment variables (
os.environ.get(...)), never hardcoded in source code.
6. A real, keyless API to try
- Public APIs that need no key exist and are safe to try locally — api.github.com is one well-known example.
- This is the one place in the chapter that describes a real network call, as an optional local exercise, not a graded one.
- Everything from Sub-topics 1-5 applies identically to a real response as it did to every simulated one so far.
GitHub's public API exposes basic information about any public repository with no API key required at all — a genuinely safe first real API call to try from a local Python installation:
import requests
response = requests.get("https://api.github.com/repos/python/cpython")
if response.status_code == 200:
data = response.json()
print(data["full_name"])
print(data["description"])
print(data["stargazers_count"], "stars")
else:
print(f"Request failed with status {response.status_code}")
api.github.com's endpoints for
public repository data are a well-known example, which is why this
chapter can reference a genuinely real API call without ever handling
a real secret.
This code is never run inside this lesson — it's presented as an
example to copy and run locally (after pip install requests,
if not already installed), specifically because this course's live
pages can't depend on every learner having internet access at every
moment. Everything about it should look completely familiar:
requests.get(), checking .status_code,
calling .json(), then navigating the result with
ordinary [key] lookups — the exact same pattern
every simulated example in this chapter has already used.
Go Deeper: rate limits on public APIs
Even keyless public APIs like GitHub's usually enforce a
rate limit — a cap on how many requests one
source can make in a given time window — specifically to keep
the service usable for everyone. Exceeding it typically returns a
403 or 429 status code rather than the
expected data, which is exactly the kind of bad-status-code case
Sub-topic 4's error handling exists to catch.
- Some real APIs are open and keyless, safe to call directly with no signup —
api.github.comis one well-known example. - The exact same
requests.get()/ status-check /.json()pattern used on every simulated response in this chapter applies unchanged to a real one. - Nothing graded in this chapter needs a live network call — this is an optional bridge to reality, not a requirement.
7. The fetch-parse-format pipeline
- Nearly every program that consumes an API follows the same three-step shape: fetch the raw response, parse it into Python data, format it for a human to read.
- Keeping the three steps as separate functions makes each one independently testable and reusable.
- This exact shape is what this chapter's project builds, end to end.
requests.get(), json.loads(), dict navigation, error handling — is a piece of one repeatable three-step shape. Seeing them combined into that shape once, explicitly, is what makes the project (and any real API-consuming program) feel like an assembly of familiar parts rather than something new.
fetch parse format
----- ----- ------
requests.get(url) --> response.json() --> build a human-readable
(or a simulated (or json.loads() on string/printout from
response, for this raw text) the parsed data
chapter's examples)
import json
# --- Step 1: fetch (simulated -- stands in for requests.get(url).text) ---
def fetch_quote_data():
return '{"quote": "Talk is cheap. Show me the code.", "author": "Linus Torvalds"}'
# --- Step 2: parse ---
def parse_quote(raw_text):
data = json.loads(raw_text)
quote = data.get("quote", "No quote available")
author = data.get("author", "Unknown")
return quote, author
# --- Step 3: format ---
def format_quote(quote, author):
return f'"{quote}"\n -- {author}'
raw = fetch_quote_data()
quote, author = parse_quote(raw)
print(format_quote(quote, author))
"Talk is cheap. Show me the code."
-- Linus Torvalds
Each function has exactly one job. fetch_quote_data()
would be the only function that changes if this switched from a
simulated string to a real requests.get() call —
parse_quote() and format_quote() wouldn't
need to change at all, since they only ever deal with already-fetched
text and already-parsed data, respectively. This separation is
exactly what makes API-consuming code testable without a network
connection: parse_quote() can be tested directly against
any hardcoded JSON string, real or fake, with identical code either
way.
- Fetch: get the raw response (a real network call, or — for every example and exercise in this chapter — a hardcoded string standing in for one).
- Parse: turn the raw text into Python data with
json.loads()(or.json()), then pull out the specific pieces needed, defensively with.get()where a key might be missing. - Format: turn that data into a readable string or printout — the part a human actually sees.
Go Deeper: this pipeline shape scales to error handling too
Sub-topic 4's status-code and network-error checks slot cleanly
into the fetch step — a real
fetch_weather_data() would wrap its
requests.get() call in a try/except
and return None (or raise a custom exception) on
failure, and the parse step would check for that
None before ever calling json.loads() on
it. The three-step shape doesn't change when error handling is
added — it just means each step has one more thing to check
before handing its result to the next one.
- Fetch, parse, and format are the three repeatable steps behind almost every API-consuming program.
- Keeping them as separate functions makes each one testable and reusable on its own, independent of whether the data came from a real network call or a hardcoded string.
- This chapter's project builds exactly this pipeline, end to end, around a menu-driven mini-app.
- Nearly every mobile app, website, and integration between two companies' software relies on a web API exchanging JSON somewhere behind the scenes — payments, maps, weather, authentication, and social features are almost never built from scratch by the app calling them.
- Real production code treats a network call as something that will eventually fail — timeouts, bad status codes, and unexpected response shapes are handled defensively, not assumed away, exactly as Sub-topic 4 covers.
- The fetch-parse-format separation from Sub-topic 7 is the same shape behind everything from a weather widget to a stock-market dashboard to a CI/CD pipeline checking a deployment's status — a small number of ingredients, combined the same repeatable way.
Points to Remember
- An API is a defined way for one program to ask another for data; a web API does this over HTTP, almost always exchanging JSON.
- A response has
.status_code(2xx success, 4xx client error, 5xx server error),.text(raw string), and.json()(parsed Python data, only valid if the body actually is JSON). json.loads(text)parses a JSON string into Python data;json.dumps(data)(optionally withindent=) converts it back, pretty-printed or compact.- Real JSON is usually nested — dicts inside lists inside dicts — navigated with ordinary chained
[key]/[index]lookups and loops. - Real API code handles network failures (
try/except requests.exceptions.RequestException), bad status codes (if response.status_code != 200:), and missing keys (.get(key, default)) — trusting none of the three by default. params=builds a query string from a dict;headers=sends metadata like an API key, always read from an environment variable, never hardcoded.- Keyless public APIs like
api.github.comexist for safe real-world practice, though nothing graded in this chapter requires a live network call. - The fetch → parse → format pipeline is the repeatable shape behind almost every real program that consumes an API.