Loading the lesson
Loading the lesson
AI & ML Engineering · Programming Foundations · Lesson 10 of 10
Requests, responses, status codes, authentication and rate limits.
Read the short notes and pictures.Do everything inside a blue frame.
Weather, payments, maps, AI models: most of what a program needs lives on someone else's server. An API is how your program asks for it.
Your program sends a request. The server sends back a response. Send a few and see what comes back.
Your program
Pick a request to send.
The API server
Waiting for a request.
2xx
200, 201It worked.
3xx
301, 304Look somewhere else.
4xx
401, 404, 429The request was wrong. Fix it on your side.
5xx
500, 503The server failed. Try again later.
You get a 503. What should your program do?
Most APIs want to know who you are. You get a key from the provider and send it with every request, in a header.
What you send
GET /users/42 Authorization: Bearer YOUR_API_KEY Accept: application/json
What comes back
200 OK
Content-Type: application/json
{ "id": 42, "name": "Asha" }1import requests23url = "https://api.example.com/users/42"4response = requests.get(url)5print(response.status_code)6data = response.json()7print(data["name"])
Press Next to run the first line.
Memory
Nothing yet
Output
Which method sends new data to the server?
Call https://api.example.com/users/42. Print the user's name when the status code is 200. Print "No such user" when it is 404.
Hint: Check response.status_code before calling response.json().
Open-Meteo gives weather for anywhere in the world, free, with no account. It is a good first API because nothing can go wrong with keys. Finding a city and getting its weather are two separate requests.
Everything after the ? in an address is a query parameter. Instead of gluing text together yourself, give requests a dict and it builds the address, including spaces and special characters.
Gluing it by hand
url = "https://geocoding-api.open-meteo.com/v1/search?name=" + name + "&count=1" response = requests.get(url)
Letting requests do it
url = "https://geocoding-api.open-meteo.com/v1/search"
response = requests.get(url, params={"name": name, "count": 1}, timeout=10)1import requests23url = "https://geocoding-api.open-meteo.com/v1/search"4response = requests.get(url, params={"name": "Pune", "count": 1}, timeout=10)5response.raise_for_status()6data = response.json()7results = data.get("results")8if results:9place = results[0]10print(place["name"], place["latitude"], place["longitude"])11else:12print("No such city")
Press Next to run the first line.
Memory
Nothing yet
Output
The wifi drops, the server is slow, the API is down. requests raises an error for each of these, and they all belong to one family: requests.RequestException. Catch that, and tell the person what happened.
ConnectionError
wifi offThe request never reached the server.
Timeout
timeout=10No answer in time.
HTTPError
raise_for_status()The server answered with a 4xx or 5xx.
RequestException
except requests.RequestExceptionThe parent of all three. One except catches them all.
Write find_city(name) that returns a dict with the name, latitude and longitude, or None when there is no match. Then call it inside try, and print "Could not reach the weather service" if any requests error happens.
Hint: The function uses params=, timeout= and raise_for_status(). The try and except go around the call, not inside the function.
Every project gets its own folder and its own virtual environment, so the packages one project installs never clash with another. requirements.txt lists them, so anyone can install the same set.
Make the environment
python -m venv .venv creates a private copy of Python in the folder .venv.
Switch it on
source .venv/bin/activate on Mac and Linux, .venv\Scripts\activate on Windows. Your prompt now starts with (.venv).
Install and record
pip install requests, then write requests in requirements.txt. Someone else runs pip install -r requirements.txt.
Keep it out of Git
Add .venv/ to .gitignore. The environment is rebuilt on each computer, never committed.
Most APIs limit how many requests you may send. Go over and you get 429 Too Many Requests. The polite fix is to wait and try again, waiting a little longer each time.
Without care
for city in cities:
r = requests.get(url, params={"q": city})
print(r.json())Waiting when told to
import time
for city in cities:
for wait in [1, 2, 4]:
r = requests.get(url, params={"q": city})
if r.status_code != 429:
break
time.sleep(wait)
print(r.json())Your script gets 429 back. What should it do?
Keep these
After the project: Working With Data