22
Day 22: Working with APIs
Chapter 22 • Advanced
55 min
APIs (Application Programming Interfaces) allow different software applications to communicate with each other. Python makes it easy to work with APIs.
What are APIs?
An API is a set of rules and protocols that allows different software applications to communicate. It's like a waiter in a restaurant - you give your order, and they bring you food.
Types of APIs:
- REST API - Representational State Transfer
- GraphQL - Query language for APIs
- SOAP - Simple Object Access Protocol
- WebSocket - Real-time communication
HTTP Methods:
- GET - Retrieve data
- POST - Create new data
- PUT - Update existing data
- DELETE - Remove data
- PATCH - Partial update
Working with APIs in Python:
- requests library - Make HTTP requests
- json library - Handle JSON data
- urllib - Built-in HTTP client
- httpx - Modern HTTP client
Common API Operations:
- Authentication - Verify user identity
- Rate Limiting - Control request frequency
- Error Handling - Manage API errors
- Data Parsing - Process response data
- Pagination - Handle large datasets
Hands-on Examples
Working with APIs
# Install requests: pip install requests
import requests
import json
# GET request example
def get_weather(city):
# Using a free weather API (example)
url = f"https://api.openweathermap.org/data/2.5/weather"
params = {
'q': city,
'appid': 'your_api_key_here', # Replace with actual API key
'units': 'metric'
}
try:
response = requests.get(url, params=params)
response.raise_for_status() # Raise exception for bad status codes
data = response.json()
return {
'city': data['name'],
'temperature': data['main']['temp'],
'description': data['weather'][0]['description']
}
except requests.exceptions.RequestException as e:
return {'error': str(e)}
# POST request example
def create_user(user_data):
url = "https://jsonplaceholder.typicode.com/users"
try:
response = requests.post(url, json=user_data)
response.raise_for_status()
return response.json()
except requests.exceptions.RequestException as e:
return {'error': str(e)}
# Working with JSON data
def process_json_data():
# Sample JSON data
json_data = '''
{
"users": [
{"id": 1, "name": "Priya", "email": "[email protected]"},
{"id": 2, "name": "Marcus", "email": "[email protected]"}
]
}
'''
# Parse JSON
data = json.loads(json_data)
# Process data
for user in data['users']:
print(f"User: {user['name']} ({user['email']})")
# Convert Python object to JSON
new_user = {"id": 3, "name": "Sofia", "email": "[email protected]"}
json_string = json.dumps(new_user, indent=2)
print("\nNew user JSON:")
print(json_string)
# Test API functions
print("Processing JSON data:")
process_json_data()This example shows how to make HTTP requests, handle JSON data, and implement proper error handling when working with APIs.