Quick wins for a faster PC:
Fix the driver behind crashes, sound loss and screen glitchesFind Drivers →Repair Windows errors before they cause bigger problemsFix Now →To make an HTTP request in Python, install the third-party requests package, call requests.get() (or another method), set a finite timeout, check the HTTP status, and then read the response as text, bytes, or JSON. This small pattern is a safe starting point:
import requests
response = requests.get(
"https://api.example.com/items",
params={"limit": 5},
timeout=10,
)
response.raise_for_status()
items = response.json()
print(items)
api.example.com is a placeholder, not a live service. Replace it with a documented endpoint whose usage terms permit your request.
How an HTTP request works
An HTTP client sends a request containing a method such as GET or POST, a URL, headers, and sometimes a body. The server returns a response with an HTTP status code, headers, and content. Receiving a response does not mean the operation succeeded: a server can return an error response just as reliably as a successful one. The Python urllib HOWTO describes this request-and-response model.
Make a GET request with Requests
1. Install the package
python -m pip install requests
Requests is a third-party library. Its current project documentation says it officially supports Python 3.10 and newer; check the Requests documentation for the version and compatibility details that apply when you install it.
Do these 3 things before closing this tab:
1Repair Windows errors before they cause bigger problems2Scan for outdated or missing drivers - takes under a minute3Clear out junk files and repair common Windows errors#1 Best Overall
2. Send the request and check the result
import requests
response = requests.get(
"https://api.example.com/items",
params={"limit": 5},
timeout=10,
)
response.raise_for_status()
items = response.json()
print(items)
paramssupplies query parameters without manually concatenating and escaping a URL.timeout=10prevents this call from waiting indefinitely.raise_for_status()raises an exception for unsuccessful HTTP status codes.json()parses a JSON response into normal Python values such as dictionaries and lists.
The example is a template rather than a claim that the placeholder endpoint works. A real API may require authentication, use another response shape, impose rate limits, paginate results, or reject an unsupported parameter.
Read the Response object
Requests returns a Response object. Use the representation that matches what the server actually sent:
| Need | API | Result |
|---|---|---|
| HTTP result | response.status_code |
Integer status such as 200 or 404 |
| Headers | response.headers |
Case-insensitive response-header mapping |
| Decoded text | response.text |
String decoded using the response encoding |
| Raw bytes | response.content |
Bytes for files or other binary data |
| JSON | response.json() |
Parsed Python value, if the body is valid JSON |
JSON parsing can fail when an endpoint returns HTML, an empty body, or malformed JSON, so parse only after checking the status and the API’s documented content type.
Rank #2
Pass query parameters correctly
For a URL such as /items?limit=5&category=books, pass structured data with params:
import requests
response = requests.get(
"https://api.example.com/items",
params={"limit": 5, "category": "books"},
timeout=10,
)
response.raise_for_status()
print(response.url)
print(response.json())
Requests performs the URL encoding. Follow the target API’s documentation for parameter names, allowed values, pagination, and maximum page sizes.
Send data with POST
Requests’ quickstart shows form-encoded data with data=:
import requests
response = requests.post(
"https://api.example.com/items",
data={"name": "Notebook"},
timeout=10,
)
response.raise_for_status()
print(response.text)
JSON APIs often expect a JSON request body instead. Use the argument and content format specified by that API; do not assume that every POST endpoint accepts form data or JSON.
response = requests.post(
"https://api.example.com/items",
json={"name": "Notebook"},
timeout=10,
)
response.raise_for_status()
Handle failures deliberately
HTTP errors
Call raise_for_status() before treating the body as usable data, or inspect response.status_code yourself when you need status-specific recovery. A 4xx response usually indicates a client-side problem such as invalid parameters or credentials; a 5xx response indicates a server-side failure, but the API’s documentation defines the precise meanings.
Network and timeout errors
A timeout, DNS failure, refused connection, or interrupted transfer is different from an HTTP error because no usable HTTP response may have arrived. Catch the exceptions appropriate for your application and decide whether a bounded retry is safe. Never remove the timeout simply to make a script wait longer.
import requests
try:
response = requests.get(
"https://api.example.com/items",
timeout=10,
)
response.raise_for_status()
data = response.json()
except requests.exceptions.Timeout:
print("The server took too long to respond")
except requests.exceptions.RequestException as exc:
print(f"Request failed: {exc}")
Use Python’s standard library with urllib.request
If installing a dependency is not appropriate, Python includes urllib.request. Python 3.13 documentation describes Requests as the recommended higher-level interface and urllib.request as the built-in, lower-level option. urlopen() accepts a URL or a Request object, takes a timeout, and returns a context-manager response.
from urllib.request import urlopen
import json
with urlopen("https://api.example.com/items?limit=5", timeout=10) as response:
if response.status != 200:
raise RuntimeError(f"HTTP status: {response.status}")
items = json.load(response)
print(items)
For headers or a different method, create a Request:
from urllib.request import Request, urlopen
request = Request(
"https://api.example.com/items",
headers={"Accept": "application/json"},
method="GET",
)
with urlopen(request, timeout=10) as response:
body = response.read()
print(body.decode("utf-8"))
The standard library provides handlers for headers, authentication, proxies, and request data, but its interface is more manual than Requests.
Best Value
Requests or urllib.request?
| Reader need | Requests | urllib.request |
|---|---|---|
| Installation | Third-party package installed with python -m pip install requests |
Included with Python |
| Common call | requests.get(), requests.post(), and related methods |
urlopen() or a Request passed to urlopen() |
| Frequent API features | Convenient parameters, JSON, headers, authentication, sessions, and timeouts | Available through a lower-level standard-library interface and handlers |
| Best fit | Approachable first choice when dependencies are acceptable | Standard-library-only projects or environments that prohibit extra packages |
Choose based on dependency policy and interface preference, not an assumed speed advantage; no performance comparison is established here.
Security and API-specific requirements
- Prefer HTTPS so credentials and data are encrypted in transit.
- Keep certificate verification enabled. Do not disable verification merely to bypass a certificate error.
- Load API keys and other credentials from a suitable secret store or environment configuration, not committed source code.
- Use the authentication mechanism, headers, pagination rules, rate limits, and permitted-use terms published by the API provider.
- Do not log authorization headers, access tokens, passwords, or sensitive response data.
Requests documents SSL verification and authentication facilities in its project documentation. The API you call remains the authority for its exact contract.
A practical beginner checklist
- Read the endpoint’s documentation and confirm that your use is allowed.
- Choose Requests for a higher-level interface or
urllib.requestwhen standard-library-only code is required. - Use HTTPS and pass query parameters or request data in the client’s structured arguments.
- Set a finite timeout on every network call.
- Check the HTTP status before parsing or storing the body.
- Parse as text, bytes, or JSON according to the documented response.
- Handle authentication, pagination, rate limits, and retries according to that API’s rules.
Further reading
The free Requests Quickstart, the Python 3.13 urllib.request documentation, and the Python urllib HOWTO cover the interfaces used here. For a structured follow-up, O’Reilly’s Learning Python Networking, Second Edition includes a beginner-level “Introduction to requests” section; buying a book is not necessary for making a first request.
Quick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.




