14. Working with APIs
Connecting to the world's data
API stands for Application Programming Interface. It's a set of rules that lets two different software systems talk to each other. When your weather app shows you tomorrow's forecast, it didn't build a satellite — it asked a weather API. When you log into a site with Google, a Google API verified your identity.
Think of an API like a waiter in a restaurant. You (the client) don't go into the kitchen (the server) to cook your own food. You tell the waiter (API) what you want, the waiter communicates with the kitchen, and brings back your food. You never need to know how the kitchen works.
Making Requests
Most web APIs use HTTP — the same protocol your browser uses to load websites. You send a request (like asking the waiter for something) and get a response back. Python's requests library makes this simple:
import requests # Make a GET request to a public API response = requests.get('https://api.coindesk.com/v1/bpi/currentprice.json') # Check if it succeeded if response.status_code == 200: data = response.json() # Parse the JSON response price = data['bpi']['USD']['rate'] print(f'Bitcoin price: {price} USD') else: print(f'Request failed: {response.status_code}')
HTTP status codes tell you what happened: 200 means success, 404 means not found, 401 means unauthorized, 500 means the server had an error. Always check the status code before using the response.
Understanding JSON
JSON (JavaScript Object Notation) is the universal language of APIs. It's a human-readable format for structured data, and it maps almost perfectly to Python dictionaries and lists:
import json # JSON string (what APIs send you) json_string = ''' { "name": "Ama Mensah", "age": 25, "courses": ["Python", "Web Dev", "Data Science"], "is_active": true } ''' # Parse JSON string into Python dictionary data = json.loads(json_string) print(data['name']) # Ama Mensah print(data['courses'][0]) # Python # Convert Python dict back to JSON string python_dict = {'city': 'Accra', 'country': 'Ghana'} json_output = json.dumps(python_dict, indent=2) print(json_output)
Using APIs in Simple Projects
Let's build something real — a program that fetches weather data and displays it nicely:
import requests def get_weather(city): # Using Open-Meteo — free, no API key needed geocode_url = f'https://geocoding-api.open-meteo.com/v1/search?name={city}' geo = requests.get(geocode_url).json() if not geo.get('results'): return f'City not found: {city}' location = geo['results'][0] lat, lon = location['latitude'], location['longitude'] weather_url = f'https://api.open-meteo.com/v1/forecast?latitude={lat}&longitude={lon}¤t_weather=true' weather = requests.get(weather_url).json() temp = weather['current_weather']['temperature'] wind = weather['current_weather']['windspeed'] return f'{city}: {temp}°C, Wind: {wind} km/h' print(get_weather('Accra')) print(get_weather('London'))
Knowledge Check
Ready to test your understanding of 14. Working with APIs?