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
Always pass timeout= to requests.get(), because a call without a timeout can freeze your notebook for a long time. Call raise_for_status() before .json(), so a 404 or 500 error stops you early instead of giving a confusing JSON error. Keep API keys in environment variables, never in a notebook cell or in Git.
Ravindra Bagale's Tip – मराठी
requests.get() ला नेहमी timeout= द्या, कारण timeout नसलेला call तुमची notebook बराच वेळ अडकवून ठेवू शकतो. .json() च्या आधी raise_for_status() चालवा, म्हणजे 404 किंवा 500 error आला तर गोंधळात टाकणाऱ्या JSON error ऐवजी काम लगेच थांबेल. API keys environment variables मध्ये ठेवा, notebook cell मध्ये किंवा Git मध्ये कधीही नको.
Ravindra Bagale's Tip – हिंदी
requests.get() में हमेशा timeout= दो, क्योंकि बिना timeout वाला call आपकी notebook को काफ़ी देर तक अटका सकता है। .json() से पहले raise_for_status() चलाओ, ताकि 404 या 500 error आने पर उलझाने वाले JSON error की जगह काम तुरंत रुक जाए। API keys को environment variables में रखो, notebook cell या Git में कभी नहीं।