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:
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:
Using APIs in Simple Projects
Let's build something real — a program that fetches weather data and displays it nicely:
Knowledge Check
Ready to test your understanding of 14. Working with APIs?