REST API Python: Calls, Tokens, Retries and Pagination

Key takeaways
Route every call through one client.py with a shared requests.Session, a (5, 30) connect and read timeout on every request, and the token read from the environment, never from source or a query string. Retry only 429 and 5xx responses, with backoff that honours Retry-After, and send a stable Idempotency-Key on writes so a retry cannot create a second record. Follow pagination to the end, guard response.json() against HTML error pages, and test the failure paths (401, 429, timeouts) before the script runs unattended.
You write a quick Python script to sync campaign links or push configuration updates from a CI pipeline. On your laptop, five test calls finish in half a second and return clean JSON. Two weeks later, the exact same script runs in GitHub Actions at 2 a.m., hits a slow upstream socket with no timeout configured, and hangs the runner until the pipeline kills it. Worse, a flaky network connection triggers a blind retry loop that posts the same record twice, leaving duplicate entries you have to clean up by hand.
Calling a REST API in Python looks effortless when a tutorial stops at requests.get() and prints a dictionary. Production failures cluster around four predictable gaps: mishandled tokens, missing timeouts, naive retries that trip rate limits or duplicate writes, and list calls that stop after page one.
I'd build one reusable client.py module from the start with session pooling, explicit timeouts, token refresh, backoff, and idempotency keys wired in. You can carry that exact file from your first 200 response straight into automated link and redirect management without rewriting a single line of networking code.
Installing Python and Making Your First REST Call#
A REST call is four inputs over HTTP and three pieces coming back. Your client sends a method (GET, POST, PUT, PATCH, or DELETE), a target URL, headers for metadata and credentials, and an optional body when the call writes data. The server answers with a numeric status code, response headers, and a body usually encoded as JSON. Methods and representations stay standard, so one client shape works against many services.
Python is a practical default for wiring those calls into backend jobs and developer tooling. In the 2025 Stack Overflow Developer Survey, 57.9% of respondents reported using Python, a 7-percentage-point increase over 2024, according to Stack Overflow's 2025 technology survey[1].
Map those four inputs to the three response parts before you write the first script. Put that mapping in a small client.py now, so the smoke test and later link automation share one request path.

Setting Up Your Environment and First Request#
You need Python 3.10 or newer, a clean virtual environment, and three libraries. Four steps get you to a verified 200 in an afternoon:
- Create and activate a virtual environment. Run
python -m venv .venv, then activate it withsource .venv/bin/activateon macOS or Linux, or.venv\Scripts\activateon Windows. Isolating packages keeps the HTTP client off the system Python that other tools depend on. - Install the core HTTP libraries. Run
pip install requests httpx python-dotenv. Userequestsfor synchronous scripts and cron jobs. Usehttpxwhen you need async concurrency or HTTP/2.python-dotenvloads local secrets from a.envfile that stays out of git. - Store configuration in
.env. PutAPI_BASE_URLandAPI_TOKENin a.envfile at the project root. The module reads them at startup, so live endpoints and secrets never sit in source. - Send a smoke-test call from
client.py. Importrequests, callrequests.get()against a public JSON endpoint withtimeout=(5, 30), and printresponse.status_codeplusresponse.json(). The tuple is connect timeout, then read timeout. A read against a public endpoint can be repeated if the socket drops. Hold retries on a write until that same module sends an idempotency key, so a repeat is the same operation rather than a second record.
pyimport requests
response = requests.get("https://httpbin.org/json", timeout=(5, 30))
print(response.status_code)
print(response.json())A 200 and parsed JSON mean the runtime, TLS certificates, and network path are fine. Keep three things next to that module for every later integration: a valid API token, the service base URL, and jq or python -m json.tool so raw payloads are readable in the terminal.
Handling Tokens and Sessions Safely#
How your Python client stores and transmits credentials is an architecture decision, not boilerplate you paste from a quickstart. Most production APIs rely on one of four authentication schemes, and each carries different operational trade-offs for rotation and expiry.
| Scheme | Where the secret lives | Expiry and refresh | Python call |
|---|---|---|---|
| Bearer token | Environment variable, sent in Authorization header | Fixed expiry, reissue manually | session.headers['Authorization'] = f'Bearer {token}' |
| API key header | Environment variable, custom header such as X-Api-Key | Usually long-lived, rotate on schedule | session.headers['X-Api-Key'] = key |
| HTTP Basic | Environment variable or vault | No expiry, rotate password | requests.get(url, auth=HTTPBasicAuth(user, pw)) |
| OAuth 2.0 client credentials | Client ID and secret in a vault | Short-lived access token, refresh via token endpoint | request token, then bearer header with cache |
Credential exposure and over-privileged access drive a growing share of real-world breaches. A recent Python API security overview[2] notes that 37% of organizations experienced API security incidents in 2024, up from 17% in 2023, pointing to broken object-level authorization and poorly managed non-human credentials as recurring attack paths.
Production Rules for Credential Placement#
When your client runs inside CI pipelines, Terraform workflows, or AI agents rather than an interactive browser, small mistakes turn into leaked production access. Enforce four hard boundaries from the beginning:
- Read secrets from
os.environor a vault: Pull credentials throughos.environ["API_TOKEN"]locally or your cloud secrets manager in production, never hardcoded inside.pyfiles. - Keep
.envout of version control: Add.envto.gitignorebefore running your firstgit commit, because an accidental push exposes tokens across every clone and CI log. - Keep tokens out of query strings: Never append
?api_key=...to a URL. Query parameters get written straight into reverse-proxy logs, server access logs, and analytics records. - Scope non-human tokens tightly: Assign CI jobs, Terraform runners, and automated agents the narrowest role that still completes the task, and rotate those credentials on a set calendar schedule.
Workspace boundaries matter just as much as storage. Prefer tokens that are scoped to one workspace and expire on a date you choose. A RedirHub API token belongs to a single workspace, is created in the dashboard, and expires after 30, 60, 90 or 180 days, one year, or never, as you pick when you create it. It can do anything the issuing workspace allows, including deleting records in bulk, so it belongs strictly on backend servers and never inside frontend browser bundles. Give a marketing automation script its own named token rather than a developer's, so it can be revoked on its own. You can review the exact header format and token scoping model in RedirHub's authentication documentation.
Caching and Refreshing Expiring Tokens#
If you integrate with an OAuth 2.0 client-credentials endpoint, requesting a new access token before every HTTP call wastes latency and trips token-endpoint rate limits. Wrap the fetch logic in a lightweight TokenCache class that reuses the active token until shortly before expiry and clears it immediately when an API replies with 401.
pyimport time
import requests
class TokenCache:
def __init__(self, token_url: str, client_id: str, client_secret: str):
self.token_url = token_url
self.client_id = client_id
self.client_secret = client_secret
self._token: str | None = None
self._expires_at: float = 0.0
def get_token(self) -> str:
if not self._token or time.monotonic() >= self._expires_at - 60:
resp = requests.post(
self.token_url,
data={"grant_type": "client_credentials"},
auth=(self.client_id, self.client_secret),
timeout=(5, 15),
)
resp.raise_for_status()
body = resp.json()
self._token = body["access_token"]
self._expires_at = time.monotonic() + int(body.get("expires_in", 3600))
return self._token
def invalidate(self) -> None:
self._token = None
self._expires_at = 0.0Subtracting 60 seconds from the expiry timestamp prevents clock-skew failures at the edge of a token's lifetime. When a request returns 401, call invalidate(), fetch a fresh token once, and retry the request before failing.
How to Write a Request and Handle the Response#
A cron job that syncs links every night will run thousands of times without supervision. Raw requests.get() calls scattered across five scripts means five places where a missing timeout or an unguarded JSON parse can hang the job or crash it. Routing every outbound call through one module named client.py gives every script connection reuse, safe parsing, and predictable error handling from the first run. A consistent seven-step workflow gets you there:
- Load base configuration at startup. Read
API_BASE_URLandAPI_TOKENfrom environment variables viaos.environand raise a clearRuntimeErrorimmediately if either is empty. - Create one shared
requests.Session(). A session reuses underlying TCP and TLS connections across requests, cutting handshake overhead and letting you attach shared headers and retry adapters in one place. - Configure default headers once. Attach
Authorization,Content-Type: application/json, andAccept: application/jsontosession.headersso individual endpoints stay concise. - Pass an explicit
timeout=(5, 30)on every call. The first number bounds connection setup (5 seconds) and the second bounds waiting for response bytes (30 seconds). Missing timeouts are the single most common reason a Python automation job hangs indefinitely. - Check
response.status_codebefore touching the payload. Treatresponse.raise_for_status()as a baseline safety net, and branch explicitly on recoverable4xxcodes instead of letting every failure collapse into one generic exception. - Guard
response.json()withtry/except json.JSONDecodeError. Misconfigured proxies, CDN edge walls, and expired sessions often return HTML pages with a200or502status, which crashes an unguarded JSON parser. - Log metadata without leaking credentials. Write method, URL, status code, and any
X-Request-Idheader atINFOlevel, while redacting theAuthorizationheader completely. A workspace token typically carries full access to everything it can reach, so a single leaked log line can expose every link in that workspace.
Treating HTTP semantics and log redaction as part of your core client matches the OWASP REST Security Cheat Sheet[3], which advises distinguishing 400, 401, 403, 404, 405, and 202 outcomes cleanly rather than masking failures behind 200 responses or leaking sensitive details in logs.
Building the Reusable client.py Module#
Paste the structure below into client.py to cover both GET reads and POST writes against any JSON REST API. Passing json=payload automatically serializes your Python dictionary and preserves the application/json content type.
pyimport json
import logging
import os
import requests
from dotenv import load_dotenv
load_dotenv()
logger = logging.getLogger(__name__)
class APIClient:
def __init__(self) -> None:
self.base_url = os.environ["API_BASE_URL"].rstrip("/")
token = os.environ["API_TOKEN"]
self.session = requests.Session()
self.session.headers.update({
"Authorization": f"Bearer {token}",
"Content-Type": "application/json",
"Accept": "application/json",
})
def request(self, method: str, path: str, **kwargs):
url = f"{self.base_url}/{path.lstrip('/')}"
kwargs.setdefault("timeout", (5, 30))
response = self.session.request(method, url, **kwargs)
req_id = response.headers.get("X-Request-Id", "none")
logger.info("%s %s -> %s (req_id=%s)", method, url, response.status_code, req_id)
if response.status_code == 204:
return None
if response.status_code >= 400:
response.raise_for_status()
try:
return response.json()
except json.JSONDecodeError as exc:
raise RuntimeError(f"Expected JSON, got: {response.text[:200]}") from exc
def get(self, path: str, params: dict | None = None):
return self.request("GET", path, params=params)
def post(self, path: str, payload: dict, headers: dict | None = None):
return self.request("POST", path, json=payload, headers=headers)Two design choices here pay off later. The request() wrapper centralizes timeout defaults and logging, so fixing a bug once fixes it for every endpoint. And returning None on 204 keeps callers from crashing on empty delete responses.
When you call list endpoints through client.get(), pair the helper with explicit page or cursor traversal so large collections don't truncate, and check the exact parameter names in RedirHub's pagination documentation before hard-coding them into your loop.
Choosing Between requests and httpx#
For CLI tools, cron scripts, and linear CI steps, requests.Session stays simple and easy to debug. When your Python service runs inside an async def web server or needs to fan out dozens of concurrent reads, switch to httpx.AsyncClient with the exact same timeout tuple and header structure. Calling a blocking synchronous client inside an async handler stalls the event loop and triggers unpredictable latency spikes, as an analysis of production Python backend frameworks[4] points out, so keep your I/O model consistent from top to bottom.
requests will wait forever on a stalled TCP socket unless you pass one explicitly.Status Codes and the Python Action for Each#
Every status code tells your client whether to parse, wait, refresh credentials, or halt. Map each response group directly to a deterministic branch in client.py:
| Status | Meaning | Python action |
|---|---|---|
| 200 / 201 | Success, resource returned or created | Parse with response.json(), continue |
| 202 | Accepted, async work queued | Poll a status endpoint with backoff, do not assume completion |
| 204 | No content | Return None, skip JSON parsing |
| 400 | Malformed input | Log the validation body, raise a local exception, do not retry |
| 401 | Missing or invalid token | Refresh or reload the token from the environment; retry once |
| 403 | Authenticated but not permitted | Stop; check workspace role and token scope |
| 404 | Resource not found | Treat as a real answer, not an error to retry |
| 405 | Method not allowed | Fix the method; check the API documentation |
| 409 | Conflict, often duplicate | Reconcile against existing state before resending |
| 422 | Schema validation failed | Print the field errors, fix the payload |
| 429 | Rate limited | Read Retry-After, sleep, retry with exponential backoff |
| 500 / 502 / 503 | Server-side failure | Retry up to 3 times with jitter, then fail loudly |
The retry column deserves a second look, because it separates reads from writes. A GET that hits a 503 is always safe to retry. A POST that timed out may already have created the resource server-side, which is why the 409 row matters: resending a write and reconciling against the conflict is usually safer than assuming the first attempt failed. That distinction is what turns this table from documentation into branching logic you can encode once and reuse.
Putting the Workflow to Work on Links and Redirects#
A marketing team is migrating a campaign site: 400 old URLs need permanent 301 redirects onto new landing pages, and 50 branded short links must change destination mid-campaign. Typing that into a web form invites typos. A script checked into git keeps the mapping next to the code that applies it.

The same client.py handles this. Timeouts, retries, and token loading stay put. Only the paths and payloads change. The RedirHub API lives at https://api.redirhub.com/v1, takes a single bearer token over JSON, and is described in the API docs from its OpenAPI 3.1 document. Call GET /test before you touch live traffic. A successful response means the token works. The token can do anything its workspace allows, so the job belongs on a server, not in a browser bundle. Edits made through the API are recorded on each link alongside dashboard changes.
Seven Steps for Safe Redirect Automation#
Run the migration in this order so bad rows fail before they change a domain:
- List existing rules with full pagination. Follow the next cursor (or page number, on APIs that use one) until the API says there is no next page. RedirHub's
GET /linksandGET /hostare cursor-paginated. Stopping on page one hides routes you already have. - Load a normalized mapping table. Each row needs
source,destination, andstatus_code, read from a version-controlled CSV or JSON file. - Send a stable idempotency key on every write. Hash the logical redirect id and put that digest in an
Idempotency-Keyheader fromclient.py. Treat the header as your client's marker for "this is the same operation." RedirHub'sPOST /linkshonours it: the same key sent again within 24 hours returns the first response instead of creating another link, a key reused for a different request returns422, and a retry while the first request is still running returns409. On APIs without that guarantee, read the resource back (or reconcile a conflict) after a timeout before you decide the write is new. - Pick the status code for the traffic, not the habit. Use
301for a permanent page move and302for a temporary campaign test.308and307match those two outcomes but keep the original method, which matters when the target is a form or an API and aPOSTmust not become aGET. - Validate every destination against a host allowlist. Parse the target and check scheme plus hostname before the payload leaves the process. A bad cell in the spreadsheet is how an open redirect gets published.
- Use bulk endpoints once the volume is real.
PUT /bulkchanges andDELETE /bulkremoves many links in one request, andPOST /bulk/summarypreviews what a bulk change will touch before you apply it. Four hundred singlePOSTs spend the rate-limit budget on overhead. - Verify a post-migration sample. Re-read 10 records at random through your
GEThelper and assert destination and status code against the local file.
The Validation and Idempotency Loop#
Host checks, a deterministic key, 429 backoff, and paginated reads sit on top of APIClient. Nothing here replaces the networking layer you already built.
pyimport hashlib
import random
import time
from urllib.parse import urlparse
import requests
ALLOWED_HOSTS = {"example.com", "shop.example.com"}
def validate_destination(url: str) -> None:
parsed = urlparse(url)
if parsed.scheme != "https" or parsed.hostname not in ALLOWED_HOSTS:
raise ValueError(f"Blocked unapproved destination: {url}")
def list_all_links(client) -> list[dict]:
items, page = [], 1
while True:
batch = client.get("/links", params={"page": page, "per_page": 100})
rows = batch.get("data", [])
if not rows:
break
items.extend(rows)
page += 1
return items
def safe_post_with_retry(client, path: str, payload: dict, logical_id: str):
idem_key = hashlib.sha256(logical_id.encode()).hexdigest()
for attempt in range(3):
try:
return client.post(path, payload, headers={"Idempotency-Key": idem_key})
except requests.HTTPError as exc:
status = exc.response.status_code
if status == 429:
wait = float(exc.response.headers.get("Retry-After", 2 ** attempt))
time.sleep(wait + random.uniform(0, 0.5))
continue
if status in (500, 502, 503):
time.sleep((2 ** attempt) + random.uniform(0, 0.5))
continue
raise
raise RuntimeError(f"Exhausted retries for {logical_id}")validate_destination() runs locally, before safe_post_with_retry() opens a socket. idem_key hashes the logical id, so a retry does not mint a new UUID inside the loop. That keeps the client's label stable across attempts. If the call times out, list or get the redirect and compare it to the mapping before you post again. A matching row means the write landed. A missing row means it is safe to send the same payload with the same key.
The list helper uses page numbers to keep the example short. Against RedirHub, pass the next cursor from each response instead, as the pagination docs describe.
Common Failures and How to Fix Them#
The bug that burns the most engineering time in production is rarely a syntax error. A silent hang on an unconfigured timeout, or a truncated list that drops half a domain's redirects without raising an exception, takes far longer to trace than any broken import. Match the frequent runtime failures to their symptoms first:
| Symptom | Likely cause | Fix |
|---|---|---|
| Script hangs indefinitely | No timeout on the request | Pass timeout=(5, 30) to every call |
| SSLCertVerificationError | Corporate proxy or missing CA bundle | Set REQUESTS_CA_BUNDLE to the corporate root CA, never verify=False |
| JSONDecodeError on a 200 | Proxy or login page returned HTML | Log the body prefix, check token expiry and redirects |
| Memory grows across calls | New Session per request | Create one Session and reuse it |
| Missing records after a list call | Pagination not followed | Loop until an empty page, log the total count |
| Duplicate links after a retry | No idempotency key | Send a stable key per logical write |
Two entries in that table deserve immediate discipline. Never silence a certificate error with verify=False: disabling TLS verification exposes your bearer token, which can do anything its workspace allows, to man-in-the-middle interception. Export REQUESTS_CA_BUNDLE=/path/to/corporate-root.pem instead. Likewise, when a requests.exceptions.Timeout fires inside an async application, check whether a blocking synchronous library slipped into an async def coroutine and swap it for httpx.AsyncClient. For payload-specific error codes returned by the server, cross-check your error parser against RedirHub's API error reference.
Benchmarking Beyond Headline Averages#
Mean latency hides the exact tail stalls that cause pipeline timeouts, so set explicit operational pass criteria before any load test starts. Define a threshold on tail latency rather than the average, plus a fixed failure-rate budget at expected peak concurrency, and hold the build to both. A redirect lookup that responds instantly on a warm cache but stalls during a rule-file refresh will pass an averaged benchmark and still time out your migration loop at 2 a.m. For redirect and link-management workloads specifically, benchmark cache hits, cache misses, rule-file refreshes, malformed URLs, and burst traffic separately so a slow refresh path can't hide behind fast cached hits.
The service at the other end sets the floor for every one of those numbers. In the RedirHub redirect speed benchmark[5] for 23 to 30 November 2026, the median time to first byte of a redirect, measured over a fresh connection from Washington, D.C., Frankfurt and Tokyo and averaged across the three, ranged from 10 ms for the fastest of 28 providers to 460 ms for the slowest. RedirHub's median was 16 ms. Those are medians, so run the same tail-latency check against whatever your script calls.
| Provider | Median time to first byte (23–30 Nov 2026) |
|---|---|
| Amazon CloudFront | 10 ms |
| Fastly | 12 ms |
| RedirHub | 16 ms |
| Cloudflare | 29 ms |
| Bitly | 113 ms |
| BL.INK | 460 ms |
Security Failures and Negative Testing#
Functional scripts still fail audits when security checks stop at TLS and valid tokens. Watch for three recurring gaps in team repositories:
- Tokens committed to git: A RedirHub workspace token acts inside one workspace only, but within that workspace it can do anything the workspace allows, including deleting records in bulk, so a leak hands over everything the token can reach. Keep tokens server-side and out of browser bundles, rotate any leaked key even after rewriting history, and add automated secret scanning to pre-commit hooks and CI checks.
- Missing object-level authorization checks: On the server side, every write endpoint must verify that the authenticated workspace owns the target domain or link, backed by an immutable audit log so cross-workspace edits fail cleanly. Scoping each token to a single workspace narrows the blast radius when one is mishandled.
- Suites that only test happy paths: A green test run means very little if your suite only stubs
200responses. Add negative tests covering expired tokens, replayed write requests, oversized payloads, and unsupported HTTP methods to prove your client fails safely under real stress. A client without negative tests is a prototype, whatever its pass rate says.
Shipping the Client to Your Team#
A script that only works on your laptop isn't shared automation; it's a future on-call interruption. Turn your working prototype into a dependable team tool by locking down five release standards before you merge.
First, keep all networking plumbing inside client.py. One reused session, connect and read timeouts on every request, a single authentication helper, and retry logic capped strictly at 429 and 5xx responses guarantee that no teammate accidentally introduces an infinite retry loop or an unguarded requests.post().
Second, prove your failure handling with automated tests. Pair pytest with the responses library (or unittest.mock) to simulate 401, 429, 404, socket timeouts, expired tokens, and oversized payloads. When CI runs those assertions on every pull request, a future refactor can't strip out your backoff or error checks.
Third, store both the Python script and the redirect mapping file in version control. A plain CSV or JSON table of sources, destinations, and status codes turns every redirect change into a reviewable pull request diff instead of an undocumented dashboard click. RedirHub records link changes on every plan, whether they come from the dashboard, the API, an AI assistant or a CSV import, and on Pro and Enterprise the audit log shows who made each one, an API token under its own name, and what it was before, so your team keeps one audit trail however a rule was updated.
Fourth, gate every write pipeline behind a pre-flight GET /test check. Confirming token validity before a migration loop starts prevents half-applied runs when a credential expires. The Management API and the RedirHub MCP server are both included on Core, Pro and Enterprise, so redirects can be managed with scripts or AI assistants alike, and that single pre-flight check protects both CI jobs and automated agent workflows.
requirements.txt, export only the documented environment variables, and run a clean dry run in five minutes, the client isn't ready to ship.Run that reproducible-checkout test on a clean directory before calling the work finished. Add your failure-path pytest cases and commit your first redirect mapping file to version control this week.
Point your Python client at one redirect API
Create, update and delete redirects, branded short links and QR codes through one JSON API with a token per workspace. Send an Idempotency-Key so a retried create never makes a second link, and preview bulk changes before they apply.
Read the API docsSources
Frequently asked questions
Install the requests library, then call requests.get() or requests.post() with the URL, your headers and a timeout such as timeout=(5, 30). Check response.status_code before reading response.json(), and keep the calls in one module so every script shares the same session, headers and error handling.
Use requests for synchronous scripts, cron jobs and CI steps. Use httpx.AsyncClient when the code runs inside an async web server or fans out many concurrent calls, because a blocking client stalls the event loop. Keep the same timeouts and headers either way.
Read it from an environment variable or a secrets manager, load a local .env file with python-dotenv, and keep .env out of git. Never hardcode it in a .py file or put it in a URL query string, where proxy and server logs record it.
Retry only 429 and 5xx responses, wait for the Retry-After header or an exponential backoff with jitter, and stop after a few attempts. For writes, send the same Idempotency-Key on every attempt, or read the resource back before resending, so a timed-out request that already succeeded is not created twice.
Keep requesting pages until the API says there are no more, passing the next cursor or page number from each response. Stopping after the first page silently drops records; RedirHub's link and domain lists are cursor-paginated.

Leo Astarothman is the Brand & Content Lead at RedirHub, where he shapes the company's visual identity, educational content, product experiences, and marketing strategies. He also specializes in system design. Simplifying complex redirect infrastructure into practical resources, product experiences, and campaigns that help businesses understand and adopt modern redirect management.
Related Articles
View All Articles


