Introduction
The requests library allows making HTTP calls to interact with web APIs.
GET Requests
import requests
# Simple GET
response = requests.get("https://api.example.com/data")
# With parameters
params = {"page": 1, "limit": 10}
response = requests.get("https://api.example.com/users", params=params)
# With headers
headers = {"Authorization": "Bearer token123"}
response = requests.get("https://api.example.com/protected", headers=headers)
Working with Response
response = requests.get("https://api.example.com/data")
print(response.status_code) # 200
print(response.headers) # Response headers
print(response.text) # Raw text
print(response.json()) # Parse JSON
# Check success
if response.ok:
data = response.json()
POST and Other Methods
# POST with JSON
data = {"name": "Alice", "email": "alice@email.com"}
response = requests.post("https://api.example.com/users", json=data)
# PUT
response = requests.put("https://api.example.com/users/1", json=data)
# DELETE
response = requests.delete("https://api.example.com/users/1")
Practice Problems
- Fetch weather data from OpenWeatherMap
- Search GitHub API for repositories
- POST new record to mock API
- Handle authentication with tokens
- Rate limiting and retries