Fetch JSON with the standard library
A small GET helper using urllib with a timeout, status check, size limit and JSON decoding errors.
- Python
- GreenSnippets
- MIT
- Executed with Python 3.11
import json
import urllib.request
def get_json(url, timeout=10, max_bytes=5_000_000, headers=None):
request = urllib.request.Request(
url, headers={"Accept": "application/json", "User-Agent": "example-client/1.0", **(headers or {})}
)
with urllib.request.urlopen(request, timeout=timeout) as response:
raw = response.read(max_bytes + 1)
if len(raw) > max_bytes:
raise ValueError("response too large")
return json.loads(raw)Example / expected output
get_json("https://api.github.com/repos/python/cpython")["full_name"] # 'python/cpython'How it works
No third-party package needed for simple GET requests. Always set a timeout (the default is none, so a stalled server blocks forever), send an explicit User-Agent and cap how much you read so a huge response cannot exhaust memory. For anything complex, requests or httpx are friendlier.
Related snippets
- JavaScript Tested
Parse the Link header for pagination
Extract next, prev, first and last page URLs from an RFC 8288 Link header like GitHub's API returns.
- JavaScript Tested
Conditional GET with ETag and 304
Compute a strong ETag for a response body and answer If-None-Match with 304 Not Modified to save bandwidth.
- JavaScript Tested
Fetch every page of a paginated API with an async generator
Iterate cursor-paginated API results with for await, loading pages lazily and stopping early when needed.
- JavaScript Tested
fetch with a timeout and error handling
Abort slow HTTP requests with AbortSignal.timeout and turn non-2xx responses into real errors.

