Python · Module 09: Concurrency, APIs & TestingTutorial 27 of 30
All Tutorials·~1.5 hrs

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.

01 Intuition: Plain-English mental model
02 Visuals: Step-by-step diagrams
03 Practice: Clean examples & tradeoffs

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):

  1. You send an HTTP Request (GET to read data, POST to create data, PUT/PATCH to update, DELETE to remove).
  2. The server replies with a Status Code + JSON Payload.
Visual: How Your Python Script Talks to Any REST API Over HTTP
Your Python Apprequests.get(url)GET /api/weather?city=Pune →← 200 OK · JSON {"temp": 28}Remote API Serverresp.json() → dict
Status CodeMeaningWhat Your Code Should Do
200 OK / 201 CreatedRequest succeeded!Parse resp.json() and use the data
400 Bad RequestYour query/body was invalidFix request parameters or payload
401 / 403Missing/invalid API key or permissionCheck Authorization header / token
404 Not FoundEndpoint or resource doesn't existHandle missing item gracefully
429 Too Many RequestsHit rate limitBack off and retry after delay
500 / 502 / 503Remote server crashed or overloadedRetry with exponential backoff

2. Production-Safe API Calls with requests

Install requests inside your .venv (pip install requests), and ALWAYS include two safety guards:

  1. timeout=5 — Without a timeout, a hung server can freeze your script forever!
  2. resp.raise_for_status() — Turns 4xx/5xx responses into clean Python exceptions immediately.
PYTHON
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:

PYTHON
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

Tracing a Safe REST API Request
Interactive Line-by-Line Execution Trace · Step 1 of 4
1→resp = requests.get("https://api.example.com/user/1", timeout=5)
2resp.raise_for_status()
3data = resp.json()
4print(f"{data['name']} ({resp.status_code})")
Variables in Memory
resp.status_code200int
Console Output
(nothing printed yet)
What just happened: Sends an HTTP GET request with a 5-second timeout and receives a 200 OK response.

Quick Quiz: Module 9.2 — APIs & HTTP

Q1.Why should EVERY `requests.get()` call include a `timeout=...` argument?
Q2.What does `resp.raise_for_status()` do?
Q3.Where should secret API keys be stored in a Python project?

Keep Exploring: Related Lessons & Tools

All Courses →