Python Lesson 22: What is an API?
An API (Application Programming Interface) is a way for programs to talk to each other over the internet. When your phone shows the weather, it uses an API. When you log in with Google, that’s an API too.
The Core Concept
# Think of an API like a restaurant:
# YOU = your program
# MENU = the API documentation
# WAITER = the API
# KITCHEN = the server/database
# You place an order (send a request)
# The waiter brings your food (returns data)
# You never see the kitchen (server stays private)
# In code:
# 1. You send an HTTP request to a URL (endpoint)
# 2. The API server processes it
# 3. The server returns data (usually JSON format)
HTTP Methods
# GET — read/fetch data (like asking for a menu)
# POST — create new data (like placing an order)
# PUT — update existing data (like changing your order)
# DELETE — remove data (like canceling an order)
# URL structure:
# https://api.example.com/users/123
# ^^^^^^^^^^^^^^ ^^^^^ ^^^
# base URL endpoint ID
API Responses and Status Codes
# Status codes tell you what happened:
# 200 OK — success!
# 201 Created — new item created
# 400 Bad Request — you sent wrong data
# 401 Unauthorized — need to login
# 403 Forbidden — no permission
# 404 Not Found — item does not exist
# 500 Server Error — the API broke
# Response data is usually JSON:
# {
# "id": 123,
# "name": "Alice",
# "email": "alice@example.com"
# }
Free Public APIs to Explore
# No API key needed (great for learning!):
# https://api.agify.io?name=alice — predicts age from name
# https://dog.ceo/api/breeds/image/random — random dog photo
# https://official-joke-api.appspot.com/random_joke — jokes
# https://wttr.in/London?format=j1 — weather
# https://catfact.ninja/fact — random cat facts
# In the next two lessons you will learn:
# 1. JSON — how API data is structured
# 2. Requests — how to call APIs from Python
🏋️ Practice Task
Visit https://api.agify.io?name=Alice in your browser. Look at the JSON response. Then change the name in the URL and see what changes. What does this API do? Write down what keys appear in the JSON response.
💡 Hint: Just open the URL in your browser. You will see raw JSON data. In Lesson 24 you will fetch this from Python code!