requests is the most popular Python library for HTTP: pip install requests.
GET
r = requests.get(url, params={"q": "python"}, timeout=10)
r.status_code— 200, 404, ...r.json()— parse JSONr.text— raw textr.headers
POST
requests.post(url, json={"name": "Asha"}) — sends JSON with the right header. Use data= for form data and files= for uploads.
Headers and auth
headers={"Authorization": f"Bearer {token}"}. Keep tokens in environment variables.
Errors
- Always set a timeout — without one, a request can hang forever
r.raise_for_status()raises an error for 4xx/5xx- Catch
requests.exceptions.RequestException
Sessions
requests.Session() reuses connections and shared headers — faster for many requests.
Async alternatives: httpx and aiohttp.
Example
import os
import requests
BASE = "https://jsonplaceholder.typicode.com"
try:
r = requests.get(f"{BASE}/posts", params={"userId": 1}, timeout=10)
r.raise_for_status()
posts = r.json()
print(f"User 1 has {len(posts)} posts. First: {posts[0]['title'][:30]}...")
new = requests.post(
f"{BASE}/posts",
json={"title": "Hello", "body": "From Python", "userId": 1},
headers={"Authorization": f"Bearer {os.getenv('API_TOKEN', '')}"},
timeout=10,
)
print(new.status_code, new.json()["id"])
missing = requests.get(f"{BASE}/posts/99999", timeout=10)
missing.raise_for_status()
except requests.exceptions.HTTPError as e:
print("HTTP error:", e.response.status_code)
except requests.exceptions.RequestException as e:
print("Network problem:", e)
Prints "User 1 has 10 posts. First: sunt aut facere...", then 201 101 for the created post, and finally HTTP error: 404 for the missing post.