October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan NowOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk5 min

Python APIs: How to Make HTTP Requests for Beginners

A beginner-friendly guide to making safe HTTP requests in Python with Requests, plus a standard-library urllib.request alternative.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

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.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

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)
  • params supplies query parameters without manually concatenating and escaping a URL.
  • timeout=10 prevents 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.

Pass query parameters correctly

For a URL such as /items?limit=5&category=books, pass structured data with params:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
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.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

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.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

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

  1. Read the endpoint’s documentation and confirm that your use is allowed.
  2. Choose Requests for a higher-level interface or urllib.request when standard-library-only code is required.
  3. Use HTTPS and pass query parameters or request data in the client’s structured arguments.
  4. Set a finite timeout on every network call.
  5. Check the HTTP status before parsing or storing the body.
  6. Parse as text, bytes, or JSON according to the documented response.
  7. 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.

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.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. Shenzhen desk3 min
    HONOR Expands Beyond Smartphones With Humanoid Robot RevealHONOR said it unveiled its first humanoid robot at MWC 2026 and named shopping assistance, workplace inspections, and supportive companionship as intended uses. Later Robotics D1 claims and a reported…
  2. Cupertino desk5 min
    Apple Unveils AirPods Max 2: The Upgrade That Should Have Happened Years AgoAirPods Max 2 adds H2-powered audio features and Apple claims up to 1.5× more effective ANC, but its design, Smart Case, and 20-hour battery rating are unchanged. Wired lossless audio…
  3. Cupertino desk4 min
    Apple’s OLED Touch MacBooks Are Coming—but the Dynamic Island Is the Real GambleApple has not announced an OLED touchscreen MacBook, but reports point to high-end models arriving in late 2026 or early 2027. The reported Mac Dynamic Island could be useful, but…
Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.