← Module 10 Module 12 β†’

🌐 Module 11

More APIs

Round two: filter requests with parameters, handle failed spells gracefully, and save what you find.

A calm teen coder catches warning paper planes with a butterfly net while a mouse carries a backup scroll.
Patch handles errors with grace, a backup plan, and one paw firmly on Enter.

πŸͺ„ The concept

Many APIs take query parameters (?rel_rhy=wand) so you can filter results. Pass a params dict to requests.get instead of hand-building messy URLs.

Network code fails. try/except with raise_for_status() keeps your program from crashing when the owl post bounces.

Some APIs need keys (like OMDB). Never paste secret keys into public repos β€” treat them like passwords. You can also save API text to a file with open(..., "w").

πŸ’¬ Discussion

Talk these through with a friend, a class, or just your notes app:

  1. Why is saving API results to a file useful when Wi-Fi is flaky?
  2. What should a friendly error message say to a player when the network fails?
  3. If an API needs a key, who should be allowed to see it?

πŸ’» Code walkthrough

Copy into your editor, or download the .py file and run it. Tinker β€” change names, numbers, and spells.

Query parameters and building a URL datamuse_rhymes.py

import requests

# Many APIs use ?key=value to filter results
base = "https://api.datamuse.com/words"
params = {"rel_rhy": "wand", "max": 3}   # words that rhyme with β€œwand”
response = requests.get(base, params=params)

if response.status_code == 200:
    words = response.json()   # list of dicts
    for entry in words:
        print(entry["word"])

Error handling for network code error_handling_for_network_code.py

import requests

try:
    r = requests.get("https://httpbin.org/status/404", timeout=5)
    r.raise_for_status()   # raises an error for 4xx/5xx responses
except requests.exceptions.HTTPError:
    print("The spell fizzled β€” page not found.")
except requests.exceptions.RequestException:
    print("No connection. Check Wi-Fi and try again.")

Search-style API (movie title lookup pattern) search_style_api_movie_title_lookup_pattern.py

import requests

# OMDB and similar services use &t= for title and often need an API key
# Sign up at omdbapi.com for a free key, then paste it below
API_KEY = "your_key_here"
title = "Harry Potter"

params = {"t": title, "apikey": API_KEY}
response = requests.get("http://www.omdbapi.com/", params=params, timeout=10)

if response.status_code == 200:
    movie = response.json()
    if movie.get("Response") == "True":
        print(movie["Title"], "(", movie["Year"], ")")
        print("Plot:", movie["Plot"][:80], "...")
    else:
        print("Movie not found:", movie.get("Error"))

Save API text to a file save_fact_to_file.py

import requests

response = requests.get("https://catfact.ninja/fact", timeout=10)
if response.status_code == 200:
    text = response.json()["fact"]
    # "w" creates/overwrites a file; always close files or use "with"
    with open("daily_fact.txt", "w", encoding="utf-8") as f:
        f.write(text)
    print("Saved to daily_fact.txt")

πŸ§ͺ Try this

  1. Change the Datamuse rhyme word from wand to another magical noun. Print up to 5 rhymes.
  2. Run the error-handling demo and confirm you see the friendly message (not a scary traceback).
  3. Save three cat facts into one text file (append mode "a" or collect in a list first). Open the file and read them back.

πŸ“ Local files

All runnable Python for this module:

module-11-apis-2/ Β· all modules

🎬 Video lesson

← Module 10 Module 12 β†’