Consuming APIs with requests
Lesson 3 of 5 · View course roadmap
Learn the idea
The requests library is the gold standard for calling APIs from Python (install with pip install requests):
import requests
resp = requests.get("https://api.github.com/users/ada-lovelace")
resp.raise_for_status() # crash loudly on 4xx/5xx
data = resp.json() # parsed JSON → dict
print(data["public_repos"])
resp.status_code,resp.json(),resp.text- Query params:
requests.get(url, params={"q": "python"}) - Sending data:
requests.post(url, json={"name": "Ada"}) - Auth: usually a header —
headers={"Authorization": "Bearer TOKEN"} - Always set a
timeout=10in production code
Note: the browser sandbox can't make real network calls, so the challenge simulates a response — the parsing skills are identical.
Where you'll use this
requests is the most-downloaded Python package in history. Fetch-parse-handle is the core loop of price trackers, chatbots, data pipelines and every integration ('sync our CRM with our billing').
Common mistakes
- No timeout:
requests.get(url)can hang forever on a dead server — production code always passestimeout=. - Calling .json() on an error page → JSONDecodeError; check
resp.status_codeor callresp.raise_for_status()first. - Building query strings by hand with f-strings —
params={...}handles encoding of spaces and special characters correctly.
Pro tip
Hammering an API in a loop gets you rate-limited (429) or banned. Real integrations add a small time.sleep() between calls and back off exponentially on 429/5xx responses.
Try it yourself
The lesson example is loaded and ready — press Run, then change something and run it again. Breaking it is part of learning. Want a clean slate? Tap “New blank”.
Output appears here…
Pass the challenge +35 XP
The starter simulates an API returning weather for three cities. Loop through the results and print each city with its temperature as City: temp°C, then print the warmest city's name.
Vilnius: 22°C Madrid: 31°C Oslo: 14°C Madrid
Use max(results, key=lambda r: r["temp"]) for the warmest.
response = {
"status": 200,
"results": [
{"city": "Vilnius", "temp": 22},
{"city": "Madrid", "temp": 31},
{"city": "Oslo", "temp": 14},
],
}
for r in response["results"]:
print(f"{r['city']}: {r['temp']}°C")
warmest = max(response["results"], key=lambda r: r["temp"])
print(warmest["city"])
Run your code to check it…
Check your understanding
Your notes (saved on this device)
Tip: use ← and → to move between lessons, ⌘K to search everything.