Session 11 Python 2025-2026 1º
Introduction to REST APIs with Python
Consuming external APIs from Python using requests, parsing JSON responses, and handling network errors robustly.
Key Concepts
- What a REST API is and how HTTP works
- HTTP methods: GET and POST
- Status codes: 200, 404, 500 and what they mean
- The
requestslibrary: installation and basic usage - Parsing and filtering JSON responses
- Handling network errors
Mandatory Part
1. Install requests
pip install requests
Verify it works:
import requests
print(requests.__version__)
2. First GET request
Make a request to a public API and inspect the response:
import requests
response = requests.get("https://jsonplaceholder.typicode.com/users")
print(response.status_code)
print(response.json())
Identify in the response: status code, headers, and JSON body.
3. Filter and display data
Parse the user list and display only name and email:
import requests
response = requests.get("https://jsonplaceholder.typicode.com/users")
if response.status_code == 200:
users = response.json()
for user in users:
print(f"{user['name']} — {user['email']}")
else:
print(f"Error: {response.status_code}")
4. Request with parameters
Filter posts by user using URL parameters:
import requests
params = {"userId": 1}
response = requests.get(
"https://jsonplaceholder.typicode.com/posts",
params=params
)
posts = response.json()
for post in posts:
print(post["title"])
5. Network error handling
Handle the most common errors:
import requests
try:
response = requests.get("https://jsonplaceholder.typicode.com/users", timeout=5)
response.raise_for_status()
data = response.json()
except requests.exceptions.ConnectionError:
print("Could not connect. Check your internet connection.")
except requests.exceptions.Timeout:
print("The request took too long.")
except requests.exceptions.HTTPError as e:
print(f"HTTP error: {e}")
Extended Part
6. Weather API
Use the Open-Meteo public API to get the current temperature in Seville:
import requests
url = "https://api.open-meteo.com/v1/forecast"
params = {
"latitude": 37.38,
"longitude": -5.97,
"current_weather": True
}
response = requests.get(url, params=params)
data = response.json()
temp = data["current_weather"]["temperature"]
print(f"Current temperature in Seville: {temp}°C")