🐍 Python for Everyone

← Back to all chapters

Chapter 19 of 27 Intermediate 75 min read

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

Picture a weather app on a phone. It doesn't have its own weather satellites or meteorologists — it sends a request to a weather company's server asking "what's the forecast for this location right now?", and that server sends back an answer. Neither side needs to know what language the other is written in, or how its internals work — they just need to agree on how to ask and how the answer is shaped. That agreement is exactly what this chapter covers: the request side (requests) and the answer's shape (JSON).
Sub-topic 1 of 7

1. What an API is, and why JSON

At a glance
  • 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.
Why this matters: every later sub-topic in this chapter is just deeper mechanics for one of these two ideas — asking a server for data (the API call) and understanding the shape of what comes back (JSON).
What is... an API? An API (Application Programming Interface) is a defined way for one piece of software to ask another for data or ask it to do something, without either side needing to know how the other is built internally. A web API is an API reached over the internet, using ordinary web requests — the same underlying technology (HTTP) a browser uses to load any web page.

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.

What is... JSON? JSON (JavaScript Object Notation) is a plain-text format for structured data that looks almost exactly like a Python dict or list written out as text — {"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.
simulated_get_demo.py
# 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())
actual output of simulated_get_demo.py
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.

What is... a status code? A status code is a 3-digit number every HTTP response includes, summarizing what happened. The ranges matter more than any individual number: 2xx means success, 4xx means the request itself was wrong somehow (a bad URL, missing permission), and 5xx means the server broke while trying to handle an otherwise-fine request.
try_it.py
Click "Run Code" — try changing status_code to 404 and see what prints instead.
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.

Quick recap
  • 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.
Sub-topic 2 of 7

2. json.loads() & json.dumps()

At a glance
  • 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.
Why this matters: a 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:

What is... "parsing"? Parsing means converting text written in some structured format into the actual data structures a program can work with — here, converting a JSON string like '{"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.
loads_dumps_demo.py
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))
actual output of loads_dumps_demo.py
<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.

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:

pretty_print_demo.py
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)
actual output of pretty_print_demo.py
{"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.

try_it.py
Click "Run Code" — try adding another key to the profile dict before printing.
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.

Quick recap
  • 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/null map to Python's True/False/None automatically in both directions.
  • json.dumps(data, indent=2) pretty-prints the same data across multiple readable lines, purely for human inspection.
Sub-topic 3 of 7

3. Navigating nested JSON

At a glance
  • 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.
Why this matters: the flat one-level dicts in Sub-topics 1-2 were kept simple on purpose to introduce 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:

the shape of a realistic weather response
{
  "city": "Austin",
  "forecast": [
    {"day": "Mon", "high_f": 88, "condition": "Sunny"},
    {"day": "Tue", "high_f": 84, "condition": "Cloudy"},
    {"day": "Wed", "high_f": 79, "condition": "Rain"}
  ]
}
What is... "nested" data? Data is nested when one data structure contains another as one of its values — a dict whose value is itself a list, whose items are themselves dicts, and so on. Nothing new is needed to navigate it: each level is just a normal [key] or [index] lookup, one level at a time, same as any dict or list already covered in Chapters 7-8.
nested_json_demo.py
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']}")
actual output of nested_json_demo.py
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.

try_it.py
Click "Run Code" — try adding a third post to the JSON string and see the total update.
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.

Quick recap
  • 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.
Sub-topic 4 of 7

4. Handling bad responses & missing keys

At a glance
  • 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 raising KeyError when a key genuinely might not be present.
  • Real API code checks for both failure modes before trusting the response contains what's expected.
Why this matters: every example so far has assumed the request succeeds and the JSON has exactly the expected keys. Real APIs go down, rate-limit callers, and change their response shape over time — code that doesn't anticipate any of that crashes in production the first time reality doesn't match the happy path.

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:

What is... a client error vs. a server error? A 4xx status code (like 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.
status_check_demo.py
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))
actual output of status_check_demo.py
{'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:

What is... 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."
request_exception_demo.py
# 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}")
actual output of request_exception_demo.py
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:

missing_key_demo.py
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}")
actual output of missing_key_demo.py
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.

try_it.py
Click "Run Code" — try removing "quote" from the dict and see the fallback kick in.
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.

Quick recap
  • A response can fail at the network level (caught with try/except requests.exceptions.RequestException) or succeed but report a bad status code (checked with if response.status_code != 200:).
  • dict.get(key, default) returns a fallback instead of raising KeyError for 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.
Sub-topic 5 of 7

5. Query params & headers

At a glance
  • 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.
Why this matters: every request so far has pointed at one fixed URL with no extra information attached. Real APIs almost always need extra input — which city's weather, which page of results, proof of who's asking — and query params and headers are the two standard ways that extra information travels alongside a request.

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:

What is... a query parameter? A query parameter is a key-value pair appended to a URL to customize a request, written after a ? (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.
params_demo.py
# 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)
actual output of params_demo.py
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:

What is... a header, and the API-key pattern? An HTTP header is a key-value pair sent alongside a request, separate from the URL — used for metadata like authentication rather than the data being requested itself. A very common pattern is an API key: a private string that identifies who's making the request, sent as a header ({"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.
headers_demo.py
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)
actual output of headers_demo.py (no WEATHER_API_KEY set)
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.

try_it.py
Click "Run Code" — try adding a fourth param and see it appended to the URL.
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.

Quick recap
  • params= passed to requests.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.
Sub-topic 6 of 7

6. A real, keyless API to try

At a glance
  • 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.
Why this matters: every example so far has deliberately avoided the network so this chapter runs identically for every learner regardless of internet access. This sub-topic is the bridge to reality — a real, working example to run locally once the mechanics feel solid, using nothing that isn't already covered.

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:

try_this_locally.py (not run in this lesson -- needs internet + requests installed)
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}")
What is... a keyless, public API? Some APIs are open for anyone to call with no signup, no API key, and no authentication at all — usually for read-only, publicly available information. 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.

Nothing graded in this chapter requires running this. The quiz, exercises, practice bank, challenges, and project all use simulated responses and run completely offline — this sub-topic exists purely as a bridge to trying the real thing once the mechanics feel solid.
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.

Quick recap
  • Some real APIs are open and keyless, safe to call directly with no signup — api.github.com is 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.
Sub-topic 7 of 7

7. The fetch-parse-format pipeline

At a glance
  • 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.
Why this matters: every individual tool in this chapter — 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.
the fetch → parse → format pipeline
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)
What is... separating fetch, parse, and format? Splitting a program into three distinct steps — fetch (get the raw response), parse (turn it into usable Python data), format (turn that data into readable output) — means each step can be tested, reused, or replaced on its own. A parse function never needs to know whether the data came from a real network call or a hardcoded test string; a format function never needs to know anything about HTTP at all.
pipeline_demo.py
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))
actual output of pipeline_demo.py
"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.

try_it.py
Click "Run Code" — try changing the JSON string in fetch_weather_data() to a different city and temperature.
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.

Quick recap
  • 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.
In the Real World

Points to Remember

← All Chapters Take the Quiz →