How to make an HTTP request in Python
Use httpx or requests. httpx is the modern successor with async support and HTTP/2. requests is the mature default.
import httpx
res = httpx.get("https://api.github.com/users/torvalds", timeout=10)
res.raise_for_status()
data = res.json()
print(data["public_repos"])httpx is a drop-in-compatible successor to requests with three real advantages: native async support (async def / await httpx.AsyncClient()), HTTP/2 out of the box, and timeout as a required default (protects against hung upstreams).
Always pass timeout= β the default in requests is None (wait forever), which turns a slow upstream into a stuck worker. 10 seconds is a reasonable ceiling for most APIs.
.raise_for_status() converts 4xx/5xx responses into an exception you can actually notice. Without it, a 500 error looks identical to a 200 until you inspect res.status_code.
Variations
POST JSON
res = httpx.post("https://api.example.com/users",
json={"name": "Alice"},
timeout=10)json= automatically serialises + sets Content-Type.
Auth header
res = httpx.get(url, headers={"Authorization": f"Bearer {token}"})Standard for API auth.
Async version
import asyncio, httpx
async def fetch():
async with httpx.AsyncClient() as c:
r = await c.get("https://api.example.com/")
return r.json()
asyncio.run(fetch())Same API, non-blocking. Requires httpx (not requests).
Get one Python lesson + one career idea every Friday
No spam, no "buy our course now". Three bullets, every Friday. Unsubscribe with one click.