Lesson 33 of 41
REST APIs for Analysts: requests, JSON Parsing & API Tokens
Overview & Learning Objectives
Modern data analysts rarely work solely with static CSV files; external data flows through REST (Representational State Transfer) APIs. Whether extracting live currency exchange rates, weather conditions, or ERP system orders, Python’s `requests` library provides an elegant HTTP client. Analysts must master request headers, authentication protocols (API keys and OAuth Bearer tokens), HTTP status code handling, and unpacking nested JSON responses directly into clean tabular DataFrames using `pd.json_normalize()`.
- Send authenticated HTTP GET and POST requests using `requests.get()` with custom headers and parameters.
- Handle HTTP response codes (200 OK, 401 Unauthorized, 429 Rate Limited, 500 Server Error) defensively via `response.raise_for_status()`.
- Flatten deeply nested JSON payloads into analytical DataFrames using `pd.json_normalize()`.
Industry Standard
Standard: Enterprise analytics teams at Stripe and Twilio mandate structured retry logic with exponential backoff on all outgoing API calls to survive intermittent network dropped connections.
Real-World Example: ScoopCraft Real-Time Weather & Demand Ingestion
ScoopCraft analytics queries OpenWeatherMap API to correlate dark-store ice cream tub sales with hourly local temperatures and rain intensity.
| API Endpoint | Auth Method | Payload Extracted | Business Value |
|---|---|---|---|
| /data/2.5/weather | Bearer Token | temp_c: 32.4, rain_1h: 0.0 | Triggers +20% inventory buffer for sorbets |
| /darkstore/inventory | API Key Header | store_id: 14, out_of_stock: 3 | Real-time dark store replenishment alert |
| /logistics/routes | OAuth2 Token | active_riders: 42, avg_eta: 14m | Calculates delivery rider availability ratio |
| /payment/status | HMAC Signature | settled_orders: 1,420, failed: 8 | Daily financial reconciliation ingestion |
Syntax & Core Code Implementation
import requests
import pandas as pd
url = 'https://api.scoopcraft.internal/v1/darkstores/orders'
headers = {
'Authorization': 'Bearer sk_live_9a8b7c6d5e4f3a2b1c',
'Accept': 'application/json'
}
params = {
'store_id': 'BLR-01',
'status': 'delivered',
'limit': 100
}
try:
response = requests.get(url, headers=headers, params=params, timeout=10)
response.raise_for_status() # Raises HTTPError for 4xx or 5xx codes
data = response.json()
# Flatten nested JSON into DataFrame
df = pd.json_normalize(data['orders'], record_path=['items'], meta=['order_id', 'delivery_time_min'])
print(f"Successfully ingested {len(df)} line items.")
except requests.exceptions.RequestException as e:
print(f"API Request Failed: {e}")
Parameters & Arguments Breakdown
url: The target API endpoint URL.headers: HTTP headers containing user-agent, content-type, or Bearer auth tokens.params: URL query parameters appended to the endpoint (e.g. ?store_id=BLR-01).timeout: Maximum seconds to wait for server response before raising Timeout exception.
Step-by-Step Implementation
- Secure API Credentials: Load API keys securely from environment variables using `os.getenv("API_KEY")`—never hardcode keys in code.
- Formulate Request: Pass query parameters as a dictionary via `params=...` so requests handles URL encoding automatically.
- Unpack JSON to DataFrame: Use `pd.json_normalize()` to flatten nested JSON structures into tabular records.
Common Mistakes & Limitations
- Omitting the `timeout` argument; if the remote server hangs, Python will freeze indefinitely and block downstream ETL pipelines.
- Hardcoding API secrets in scripts that get committed to public Git repositories.
- Checking success with `response.status_code == 200` manually instead of calling `response.raise_for_status()`, which handles all 2xx success ranges and raises informative errors.
Keyboard Shortcuts (Jupyter & VS Code)
| Action | Windows | Mac |
|---|---|---|
| Paste formatted curl or JSON payload in VS Code | Ctrl + Shift + V | Cmd + Shift + V |
Pro Tips & Modern Best Practices
- Use `requests.Session()` across multiple requests to reuse TCP connections, improving request latency by 2x-3x through HTTP Keep-Alive.
- Leverage `pd.json_normalize(..., sep="_")` to cleanly name flattened nested child keys (e.g. `customer_address_pincode`).