Python and APIs
Learn how to use the requests library to interact with web APIs, send GET and POST requests, and parse JSON responses.
What is an API?
An API (Application Programming Interface) allows programs to communicate with each other. Web APIs use HTTP requests to send and receive data, usually in JSON format. Your Python program acts as the client, and the API is the server.
import requests
# Simple GET request to a public API
response = requests.get("https://api.agify.io?name=michael")
# Check if the request was successful
print(response.status_code) # 200 = success
# Parse the JSON response
data = response.json()
print(data)
# {'count': 233482, 'name': 'michael', 'age': 62}
# Access specific fields
print(f"Name: {data['name']}")
print(f"Predicted age: {data['age']}")
Install the requests library with pip install requests. It is not included in Python's standard library.
GET and POST Requests
GET requests retrieve data from a server. POST requests send data to a server (e.g., form submissions, creating resources). The requests library makes both straightforward.
import requests
# GET with query parameters
params = {"lat": -33.8688, "lon": 151.2093} # Sydney
response = requests.get(
"https://api.open-meteo.com/v1/forecast",
params={**params, "current_weather": True}
)
weather = response.json()
temp = weather["current_weather"]["temperature"]
print(f"Sydney temperature: {temp} C")
# POST request (sending data)
response = requests.post(
"https://httpbin.org/post",
json={"student": "Alice", "score": 95}
)
print(response.status_code) # 200
print(response.json()["json"])
# {'student': 'Alice', 'score': 95}
# Headers for authentication
headers = {"Authorization": "Bearer YOUR_API_KEY"}
response = requests.get("https://api.example.com/data",
headers=headers)
Error Handling and JSON Parsing
API calls can fail due to network issues, invalid URLs, or rate limits. Always check the status code and handle errors gracefully. Use try/except for robust code.
import requests
import json
def fetch_data(url):
"""Fetch data from an API with proper error handling."""
try:
response = requests.get(url, timeout=10)
response.raise_for_status() # raises for 4xx/5xx
return response.json()
except requests.exceptions.Timeout:
print("Error: Request timed out")
except requests.exceptions.HTTPError as e:
print(f"HTTP Error: {e.response.status_code}")
except requests.exceptions.ConnectionError:
print("Error: Could not connect to server")
except json.JSONDecodeError:
print("Error: Response was not valid JSON")
return None
# Common status codes:
# 200 = OK, 201 = Created, 400 = Bad Request
# 401 = Unauthorized, 404 = Not Found, 500 = Server Error
data = fetch_data("https://api.agify.io?name=alice")
if data:
print(f"Success: {data}")
Key Vocabulary
API
Application Programming Interface - a set of rules that allows programs to communicate with each other over a network.
JSON
JavaScript Object Notation - a lightweight data format used by most APIs. Maps directly to Python dictionaries and lists.
HTTP Status Code
A numeric code returned by the server indicating the result (200 = OK, 404 = Not Found, 500 = Server Error).
Endpoint
A specific URL path on an API server that handles a particular type of request (e.g., /users, /weather).
Worked Examples
Fetch and display random user data
import requests
response = requests.get("https://randomuser.me/api/")
data = response.json()
user = data["results"][0]
name = f"{user['name']['first']} {user['name']['last']}"
email = user["email"]
country = user["location"]["country"]
print(f"Name: {name}")
print(f"Email: {email}")
print(f"Country: {country}")
# Name: Sarah Johnson
# Email: [email protected]
# Country: Australia
Key point: API responses are often nested JSON. Navigate using dictionary keys and list indices to reach the data you need.
Build a simple weather checker
import requests
def get_weather(city_lat, city_lon, city_name):
"""Get current weather using Open-Meteo API."""
url = "https://api.open-meteo.com/v1/forecast"
params = {
"latitude": city_lat,
"longitude": city_lon,
"current_weather": True
}
response = requests.get(url, params=params)
if response.status_code == 200:
weather = response.json()["current_weather"]
print(f"Weather in {city_name}:")
print(f" Temperature: {weather['temperature']} C")
print(f" Wind speed: {weather['windspeed']} km/h")
else:
print(f"Error: {response.status_code}")
get_weather(-33.87, 151.21, "Sydney")
get_weather(-37.81, 144.96, "Melbourne")
Query parameters are passed as a dictionary to the params argument. The requests library handles URL encoding automatically.
Save API data to a JSON file
import requests
import json
# Fetch data from API
response = requests.get("https://api.agify.io?name=sarah")
data = response.json()
# Save to file
with open("api_response.json", "w") as f:
json.dump(data, f, indent=2)
print("Data saved to api_response.json")
# Read it back
with open("api_response.json", "r") as f:
loaded = json.load(f)
print(f"Loaded: {loaded}")
# Loaded: {'count': 200345, 'name': 'sarah', 'age': 34}
json.dump() writes Python data to a JSON file. json.load() reads it back. Use indent=2 for readable formatting.
Knowledge Check
Select the correct answer for each question. Click "Check Answer" to see if you are right.
Question 1
What HTTP method is used to retrieve data from an API?
Question 2
What does response.json() return?
Question 3
What HTTP status code means "Not Found"?
Question 4
Which parameter in requests.post() sends JSON data?
Question 5
What does response.raise_for_status() do?
Key Concepts Summary
- ●APIs allow programs to exchange data over the internet using HTTP requests.
- ●GET retrieves data; POST sends data. Use the
requestslibrary for both. - ●JSON is the standard data format for APIs and maps directly to Python dicts and lists.
- ●Always check status codes and use try/except for robust error handling.
- ●Use json.dump() and json.load() to save and read API data to/from files.