Use requests.get("https://api.example.com/data", timeout=10) from the third-party requests library (pip install requests) for the cleanest one-liner with built-in .json() decoding, query parameter encoding, and status checks, or urllib.request.urlopen("https://api.example.com/data", timeout=10) from Python’s built-in standard library when zero external packages are allowed.
Basic Example
# 1. Recommended (`requests` — cleanest syntax, automatic JSON decoding & query params):
import requests
response = requests.get(
"[https://httpbin.org/get](https://httpbin.org/get)",
params={"page": 1, "limit": 20},
timeout=10,
)
response.raise_for_status() # Raises HTTPError on 4xx / 5xx responses
data = response.json()
print(response.status_code, data["args"])
# Output: 200 {'limit': '20', 'page': '1'}
# 2. Zero-dependency Standard Library (`urllib.request`):
import json
from urllib.request import urlopen
with urlopen("[https://httpbin.org/get?page=1&limit=20](https://httpbin.org/get?page=1&limit=20)", timeout=10) as resp:
payload = json.loads(resp.read().decode("utf-8"))
print(resp.status, payload["args"])
# Output: 200 {'limit': '20', 'page': '1'}
Key Details & Edge Cases
- Always pass
timeout=10(bothrequestsandurllib):requests.get(url)defaults totimeout=None(no timeout), which can hang a script indefinitely if an upstream server stalls. Always includetimeout=10(ortimeout=(3.05, 10)for separate connect/read limits).
requestsdoes NOT raise on404or500automatically, whereasurllib.request.urlopenDOES:requests.get()returns aResponseobject even on404 Not Foundor500 Internal Server Error—always callresponse.raise_for_status()before readingresponse.json(). Conversely,urllib.request.urlopen()automatically raisesurllib.error.HTTPErroron any status code $\ge 400$.
- Reuse a
requests.Session()when making multiple requests to the same host:- Calling
requests.get()repeatedly opens and closes a new TCP/TLS connection on every call. Wrapping multiple requests insidewith requests.Session() as s:reuses underlyingurllib3keep-alive connections and shares headers/cookies, cutting latency dramatically.
- Calling
- When you need
async/awaitconcurrency (httpx/aiohttp):- Both
requestsandurllib.requestare synchronous (blocking). For concurrentasyncioHTTP GET requests, usehttpx.AsyncClient()(which mirrors therequestsAPI almost identically) oraiohttp.ClientSessio().
- Both
- Custom
User-Agentheaders for public endpoints:- Some APIs and websites block default
python-requests/...orPython-urllib/...user agents with403 Forbidden; passheaders={"User-Agent": "my-app/1.0"}if an endpoint rejects default client headers.
- Some APIs and websites block default
Comparison of HTTP GET Libraries in Python
| Library | Installation | Built-In .json() & Query params=? |
Supports async / await? |
Best Used When |
|---|---|---|---|---|
requests (Recommended) |
pip install requests |
Yes (resp.json(), params=) |
No (synchronous) | General Python scripts, REST API clients, and quick one-liners. |
urllib.request |
Built-in (Standard Library) | No (manual json.loads & urlencode) |
No (synchronous) | Minimal environments, AWS Lambda/CLI tools, or bootstrap scripts with zero dependencies. |
httpx |
pip install httpx |
Yes (requests-compatible API) |
Yes (httpx.AsyncClient) |
Modern asyncio applications or codebases needing HTTP/2 and async support. |
aiohttp |
pip install aiohttp |
Yes (await resp.json()) |
Yes (async-only) | High-concurrency async web scrapers and microservices handling thousands of requests. |
You must log in or register to comment.
