Part 12 / Topic 4 of 11
The requests library (side by side)
urllib works, but it is wordy. requests is a third-party package (Part 7) that most Python developers use for HTTP. It does the encoding, JSON and headers for you.
Think of urllib as cooking from raw ingredients and requests as a ready meal kit: same food, less work.
Install it inside a virtual environment (Part 7):
python -m venv .venv
source .venv/bin/activate # Windows: .venv\Scripts\activate
pip install requests
⚠️
requestscode (not run by the examples). The examples and solutions of this part use only the standard library. Therequestslines below are for reading and for your own projects.
| Task | urllib.request (stdlib) |
requests (third-party) |
|---|---|---|
| GET with params | urlopen(url + "?" + urlencode(params), timeout=5) |
requests.get(url, params=params, timeout=5) |
| Read JSON | json.load(response) |
response.json() |
| Status code | response.status |
response.status_code |
| POST JSON | build Request(url, data=json.dumps(d).encode(), headers=..., method="POST") |
requests.post(url, json=d, timeout=5) |
| Send a header | Request(url, headers={"X-API-Key": key}) |
requests.get(url, headers={"X-API-Key": key}) |
| Error on 4xx/5xx | raised automatically as HTTPError |
call response.raise_for_status() |
| Base error class | urllib.error.URLError |
requests.RequestException |
The same calls as the urllib.request topic, with requests:
# requires: pip install requests (and a running API at base_url)
import requests
response = requests.get(
base_url + "/api/products",
params={"category": "kitchen", "max_price": 500}, # encoded for you
timeout=5,
)
response.raise_for_status() # raises requests.HTTPError on 4xx/5xx
data = response.json() # body -> dict
print(response.status_code, data["count"]) # 200 2
response = requests.post(
base_url + "/api/orders",
json={"product_id": 2, "quantity": 2}, # dumps + header for you
timeout=5,
)
print(response.status_code, response.json()["total"]) # 201 3798
try:
requests.get(base_url + "/api/products/99", timeout=5).raise_for_status()
except requests.HTTPError as error:
print(error.response.status_code) # 404
except requests.RequestException as error: # cannot connect, timeout ...
print("Network problem:", error)
⚠️ Unlike
urllib,requestsdoes not raise on a 404 or 500 by itself. Always callraise_for_status()(or checkstatus_code).
🔍 Going deeper:
requests.Session()reuses one connection for many calls (faster) and keeps headers like your API key for every request. Forasynccode there ishttpx(Stage 3).
Done here? The practice set for Part 12 — 8 exercises with solutions — is on the part page.