Introduction to APIs
Learn what APIs are and how to use them in Python
Introduction to APIs
What is an API?
API stands for Application Programming Interface. It's a way for programs to talk to each other over the internet.
Simple explanation: Think of an API like a waiter in a restaurant. You tell the waiter what you want, the waiter tells the kitchen, and the kitchen sends back your food.
In programming:
- You (Python program) make a request
- API receives your request
- Server processes it
- API sends back data
Why Use APIs?
Get real-time data:
- Weather information
- Stock prices
- News articles
- Social media posts
Use services:
- Send emails
- Process payments
- Translate text
- Get maps and directions
Integrate systems:
- Connect your app to other apps
- Share data between programs
- Automate tasks
REST APIs
REST is the most common API type. It uses HTTP (like websites).
REST uses URLs:
REST uses methods:
- GET: Get data (read)
- POST: Send data (create)
- PUT: Update data
- DELETE: Remove data
API Responses
APIs usually send data as JSON.
Example response:
{
"name": "John Doe",
"email": "john@example.com",
"age": 25
}The requests Library
Python's requests library makes API calls easy.
Install it first:
pip install requests
Then import:
import requestsMaking Your First API Call
import requests
response = requests.get("https://api.github.com")
print("Status code:", response.status_code)
print("Data:", response.json())What this does:
- Makes GET request to GitHub API
- Gets status code (200 means success)
- Converts response to Python dictionary
Status Codes
Status codes tell you if request worked.
Common codes:
- 200: Success
- 201: Created successfully
- 400: Bad request (you sent wrong data)
- 401: Not authorized (need login)
- 404: Not found
- 500: Server error
import requests
response = requests.get("https://api.example.com/data")
if response.status_code == 200:
print("Success!")
data = response.json()
elif response.status_code == 404:
print("Not found")
else:
print("Error:", response.status_code)Getting JSON Data
import requests
response = requests.get("https://api.github.com/users/octocat")
if response.status_code == 200:
user = response.json()
print("Name:", user["name"])
print("Bio:", user["bio"])
print("Public repos:", user["public_repos"])What .json() does: Converts JSON response to Python dictionary.
URL Parameters
Add parameters to customize requests.
import requests
params = {
"city": "London",
"units": "metric"
}
response = requests.get("https://api.weather.com/data", params=params)What this creates: https://api.weather.com/data?city=London&units=metric
Headers
Headers send extra information with requests.
import requests
headers = {
"User-Agent": "MyApp/1.0",
"Accept": "application/json"
}
response = requests.get("https://api.example.com", headers=headers)Common headers:
- User-Agent: Identifies your program
- Accept: What data format you want
- Authorization: API key or token
Error Handling
Always handle errors when working with APIs.
import requests
try:
response = requests.get("https://api.example.com/data")
response.raise_for_status()
data = response.json()
print(data)
except requests.exceptions.HTTPError as e:
print("HTTP error:", e)
except requests.exceptions.ConnectionError:
print("Connection error")
except requests.exceptions.Timeout:
print("Request timed out")
except requests.exceptions.RequestException as e:
print("Error:", e)What raise_for_status() does: Raises error if status code is 400 or higher.
Timeout
Prevent requests from waiting forever.
import requests
try:
response = requests.get("https://api.example.com/data", timeout=5)
print(response.json())
except requests.exceptions.Timeout:
print("Request took too long")What timeout=5 means: Wait maximum 5 seconds for response.
Practice Example
The scenario: Get weather data from a free API.
import requests
def get_weather(city):
base_url = "https://api.openweathermap.org/data/2.5/weather"
params = {
"q": city,
"appid": "your_api_key_here",
"units": "metric"
}
try:
response = requests.get(base_url, params=params, timeout=10)
response.raise_for_status()
data = response.json()
print("City:", data["name"])
print("Temperature:", data["main"]["temp"], "°C")
print("Description:", data["weather"][0]["description"])
print("Humidity:", data["main"]["humidity"], "%")
except requests.exceptions.HTTPError as e:
if response.status_code == 404:
print("City not found")
else:
print("HTTP error:", e)
except requests.exceptions.RequestException as e:
print("Error:", e)
get_weather("London")What this program does:
- Builds API URL with parameters
- Makes request with timeout
- Checks for errors
- Parses JSON response
- Displays weather information
- Handles various error types
Note: You need to sign up at openweathermap.org for free API key.
Checking Response Content Type
import requests
response = requests.get("https://api.example.com/data")
print("Content Type:", response.headers["Content-Type"])
if "application/json" in response.headers["Content-Type"]:
data = response.json()
else:
print("Response is not JSON")Why this matters: Ensures response is JSON before trying to parse it.
Key Points to Remember
APIs let programs communicate over the internet. REST APIs use HTTP and usually return JSON.
Use requests library for API calls. Install with pip install requests.
GET method retrieves data. Check status_code to see if request succeeded (200 is success).
Use .json() to convert response to Python dictionary. Always handle errors with try-except.
Add timeout to prevent waiting forever. Most APIs require API keys for access.
Common Mistakes
Mistake 1: Not checking status code
response = requests.get(url)
data = response.json() # May fail if request failed!Mistake 2: No error handling
response = requests.get(url) # Program crashes if network failsUse try-except.
Mistake 3: No timeout
response = requests.get(url) # May wait forever!
response = requests.get(url, timeout=10) # BetterMistake 4: Hardcoding API keys
api_key = "12345" # Don't put in code!Use environment variables or config files.
What's Next?
You now understand API basics. Next, you'll learn about making API requests - sending data with POST, updating with PUT, and working with authentication.