π Module 11
More APIs
Round two: filter requests with parameters, handle failed spells gracefully, and save what you find.
πͺ 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:
- Why is saving API results to a file useful when Wi-Fi is flaky?
- What should a friendly error message say to a player when the network fails?
- 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
- Change the Datamuse rhyme word from
wandto another magical noun. Print up to 5 rhymes. - Run the error-handling demo and confirm you see the friendly message (not a scary traceback).
- 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: