🦉 Module 10
Connecting to an API
Your programs can ask the internet for live data. An API is like owl post for computers.
🪄 The concept
An API is a service that returns data (often JSON) when you request a URL. The requests library helps you get that data in Python (pip install requests).
Check status_code == 200 (OK), then .json() turns the response into dicts and lists you already know how to loop.
Nested JSON is just nested dictionaries/lists — walk key by key, then loop when you hit a list of results.
💬 Discussion
Talk these through with a friend, a class, or just your notes app:
- What live data would make a school project cooler? (weather, space station location, trivia…)
- Why check status codes instead of assuming every request works?
- Is data from the internet always trustworthy? What would you double-check?
💻 Code walkthrough
Copy into your editor, or download the .py file and run it. Tinker — change names, numbers, and spells.
Fetching JSON from an API (pip install requests) advice_api.py
import requests
# APIs return live data — here we ask a free “advice” service for a quote
url = "https://api.adviceslip.com/advice"
response = requests.get(url)
# Check status — 200 means OK
if response.status_code == 200:
data = response.json() # parse JSON into a Python dict
print("Hermione says:", data["slip"]["advice"])
else:
print("Could not reach the owl post:", response.status_code)Working with nested JSON working_with_nested_json.py
# Many APIs nest data — use keys step by step
# Example structure (your real API may look different):
iss_position = {
"iss_position": {"latitude": "45.1234", "longitude": "-75.5678"},
"timestamp": 1710000000
}
lat = iss_position["iss_position"]["latitude"]
lon = iss_position["iss_position"]["longitude"]
print("International Space Station near:", lat, lon)Loop through a list inside JSON loop_through_a_list_inside_json.py
# Many APIs return a list of objects — loop and print each one
# (sample data — real API responses look similar)
trivia = {
"results": [
{"question": "What is the counter-spell to Lumos?", "answer": "Nox"},
{"question": "Who teaches Transfiguration?", "answer": "McGonagall"}
]
}
for item in trivia["results"]:
print("Q:", item["question"])
print("A:", item["answer"])
print("---")Cat facts API (no API key required) cat_fact.py
import requests
url = "https://catfact.ninja/fact"
response = requests.get(url, timeout=10)
if response.status_code == 200:
fact = response.json()
print("Did you know?")
print(fact["fact"])
else:
print("Could not fetch fact:", response.status_code)🧪 Try this
- Run
advice_api.pythree times. Did the advice change? - Run
cat_fact.py, then change the print message to sound like a Hogwarts librarian announcing the fact. - Browse a public API list (linked on the course page) and sketch which keys you would dig into first.
📁 Local files
All runnable Python for this module: