← Module 9 Module 11 →

🦉 Module 10

Connecting to an API

Your programs can ask the internet for live data. An API is like owl post for computers.

A mechanical pigeon carries a glowing data capsule between a brass computer and a cloud library.
Rowan sent a request into the wide web. The dragon is waiting for the response in strict loaf position.

🪄 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:

  1. What live data would make a school project cooler? (weather, space station location, trivia…)
  2. Why check status codes instead of assuming every request works?
  3. 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

  1. Run advice_api.py three times. Did the advice change?
  2. Run cat_fact.py, then change the print message to sound like a Hogwarts librarian announcing the fact.
  3. 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:

module-10-apis/ · all modules

🎬 Video lesson

← Module 9 Module 11 →