26. How to Read APIs, JSON and Zipped CSVs into pandas
26.2 requests Basics: Timeout and Status
Why. A hung GET without timeout freezes Jupyter. Ignoring status codes turns an HTML error page into a “JSON parse” mystery.
What.
requests.get(url, timeout=30)— always set a timeout.response.status_code/response.raise_for_status()— fail loud on 404/500.- Headers may carry an API key — load from environment variables, not from a shared cell.
How.
First safe GET
pip install requestsonce in your venv (if needed).- Store tokens in env vars (
os.environ). - Call
getwithtimeout=. - Check status before
.json(). - Save raw JSON to
data/raw/for replay offline.
Worked example A — Local fake JSON file (no network).
import json
from pathlib import Path
Path("data/raw").mkdir(parents=True, exist_ok=True)
payload = {
"generated_at": "2026-10-24T16:00:00+05:30",
"orders": [
{"order_id": "BLK-1", "city": "Pune", "status": "Delivered", "amount_inr": 189},
{"order_id": "BLK-2", "city": "Nashik", "status": "Open", "amount_inr": 95},
{"order_id": "AMN-3", "city": "Kolhapur", "status": "Delivered", "amount_inr": 210},
],
}
path = Path("data/raw/status_sample.json")
path.write_text(json.dumps(payload, indent=2), encoding="utf-8")
print("wrote", path)
Worked example B — requests shape (classroom URL placeholder).
import os
import requests
# Classroom only — replace with a practice URL your trainer gives.
url = os.environ.get("DS_STATUS_URL", "https://httpbin.org/json")
r = requests.get(url, timeout=30)
print("status", r.status_code)
r.raise_for_status()
data = r.json()
print(type(data), list(data)[:5] if isinstance(data, dict) else "list")
Worked example C — Who holds the key (fictional).
| Person | Holds |
|---|---|
| Ravindra Bagale (learner) | Read-only practice token in env |
| Shared GitHub repo | No tokens |
| Screenshot on WhatsApp | Crop secrets before send |
Ravindra Bagale's Tip
Timeout = seatbelt. raise_for_status = early alarm. Key Git madhe nahi.