Requests
Requests is the widely used third-party HTTP client for Python. requests.get(url) returns a Response with status, headers, and body helpers. It is synchronous and blocking.
Detailed Explanation
The one-liner requests.get("https://api.example.com/orders") hides connection pooling, cookies, and encoding. For more than one call, use requests.Session(): it keeps a connection pool and a cookie jar, and it is the place to set a default timeout, a base header, and retries (via an adapter).
Always pass timeout=(connect, read) or a single number. The default is "wait forever". Always check resp.raise_for_status() or resp.status_code before you resp.json(). A 500 HTML body will fail in json() with a confusing error if you skip the status.
params= is the query string. json= serialises a body and sets Content-Type. data= sends form-encoded or raw bytes. files= is multipart. Do not build JSON with data=json.dumps(...) unless you also set the header; use json=.
Sessions are not thread-safe if you mutate them. They are fine from one thread. In asyncio, Requests blocks the loop; use httpx.AsyncClient or aiohttp, or wrap the call in asyncio.to_thread.
Trust the environment's CA bundle by default. verify=False disables TLS verification and is a last resort for a broken lab, never for production. proxies= and HTTP_PROXY affect where the traffic goes; be explicit in servers.
Requests is not in the standard library. Pin it. urllib.request is the stdlib alternative and is more verbose. httpx is the modern dual sync/async client with a similar API.
Code Examples
import requests
def fetch_order(order_id: str, session: requests.Session) -> dict:
resp = session.get(
f"https://api.example.com/orders/{order_id}",
timeout=(2, 5),
)
resp.raise_for_status()
return resp.json()
# with requests.Session() as session:
# session.headers["Authorization"] = "Bearer token"
# print(fetch_order("11", session))resp = requests.Response()
resp.status_code = 404
try:
resp.raise_for_status()
except requests.HTTPError as exc:
print(exc.response.status_code) # 404Common Gotchas
No timeout
a dropped packet holds a worker forever. Always set one.
`resp.json()` on an error HTML page
catch status first.
`verify=False`
anyone on the path can MITM you. Fix the certificate.
`requests` in a coroutine blocks the event loop
use an async client or a thread.