Free lab Real Python 3. Zero installs. Your code stays in this browser. Open the playground

Consuming APIs with requests

16 min 35 XP
Study loop Read Predict Run Tweak Prove Review
Lesson 3 of 5 · View course roadmap
Step 1

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=10 in 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 passes timeout=.
  • Calling .json() on an error page → JSONDecodeError; check resp.status_code or call resp.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.

Step 2

Try it yourself

Blank · autosaved

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”.

PYexample.py
+ Enter to run
Output appears here…
Step 3

Pass the challenge +35 XP

Blank · autosaved

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.

Target output
Vilnius: 22°C
Madrid: 31°C
Oslo: 14°C
Madrid
PYchallenge.py
Run your code to check it…
Step 4

Check your understanding

1. What does resp.json() return?
2. Where does a Bearer token usually go?
Last step

Your notes (saved on this device)

Tip: use and to move between lessons, K to search everything.

Your next ten minutes

Write Python that does something useful.

Start free. No install, no card, no passive video marathon.

Start learning free → Explore the path