9.2 Working with REST APIs, HTTP, JSON & Environment Secrets (.env)
Connect your Python scripts to the real world! Master HTTP methods, status codes, calling REST APIs safely with timeouts & error checks, and protecting API keys with .env.
1. How APIs Work (The Restaurant Waiter Analogy)
An API (Application Programming Interface) is like a waiter between your Python app (the customer) and a remote server (the kitchen):
- You send an HTTP Request (
GETto read data,POSTto create data,PUT/PATCHto update,DELETEto remove). - The server replies with a Status Code + JSON Payload.
| Status Code | Meaning | What Your Code Should Do |
|---|---|---|
200 OK / 201 Created | Request succeeded! | Parse resp.json() and use the data |
400 Bad Request | Your query/body was invalid | Fix request parameters or payload |
401 / 403 | Missing/invalid API key or permission | Check Authorization header / token |
404 Not Found | Endpoint or resource doesn't exist | Handle missing item gracefully |
429 Too Many Requests | Hit rate limit | Back off and retry after delay |
500 / 502 / 503 | Remote server crashed or overloaded | Retry with exponential backoff |
2. Production-Safe API Calls with requests
Install requests inside your .venv (pip install requests), and ALWAYS include two safety guards:
timeout=5— Without a timeout, a hung server can freeze your script forever!resp.raise_for_status()— Turns4xx/5xxresponses into clean Python exceptions immediately.
import requests
def fetch_github_user(username: str) -> dict | None:
url = f"https://api.github.com/users/{username}"
try:
resp = requests.get(
url,
headers={"Accept": "application/vnd.github+json"},
timeout=5,
)
resp.raise_for_status()
return resp.json()
except requests.Timeout:
print("Request timed out — try again later.")
except requests.HTTPError as err:
print(f"HTTP error: {err}")
return None
3. Never Hardcode API Keys! Use Environment Variables (.env)
If you hardcode API_KEY = "sk-live-..." and push to GitHub, bots scrape and abuse your key in under 60 seconds!
Instead, put secrets in a local .env file (listed in .gitignore) and read them via os.environ:
import os
# Load from environment (or use `python-dotenv` -> load_dotenv())
api_key = os.environ.get("WEATHER_API_KEY")
if not api_key:
raise RuntimeError("Missing WEATHER_API_KEY environment variable!")
4. Interactive Trace: Fetching & Parsing a JSON API Response
Quick Quiz: Module 9.2 — APIs & HTTP
Keep Exploring: Related Lessons & Tools
All Courses →Validate, prettify, minify, sort keys, explore interactive collapsible JSON trees, and generate TypeScript interfaces instantly.
Convert Unix epoch seconds/milliseconds to ISO-8601 and local timezones, and bulk-generate UUID v4, time-ordered UUID v7, and sortable ULIDs.