Calling HTTP APIs with requests
Call REST APIs with auth, retries and error handling.
By Invicly Tech, , in Full DevOps with Python. About 11 minutes to read.
In short
The requests library makes calling REST APIs simple. Real automation also needs timeouts, auth headers, status checks, retries with backoff and pagination.
Explained simply
Most tools you automate have an HTTP API: GitHub, Slack, cloud providers, monitoring systems. Your script sends a request (a method like GET or POST plus a URL) and gets back a response with a status code and usually some JSON. The requests library makes this a one-liner.
Most APIs want to know who you are. You usually send a token in a header, a small labelled line attached to the request, like Authorization: Bearer abc123. Keep tokens in environment variables or a secret store, never in the code or in logs.
Networks fail in boring, everyday ways: a server is slow, a connection drops, an API says "too many requests". A robust script expects this. It sets a timeout so it never hangs, checks the status code, and retries temporary failures after a short wait.
Big result sets come in pages, for example 100 items at a time. Your script keeps asking for the next page until the API says there are no more. Once you have these habits, any API becomes easy to automate.
Press Play on a diagram to walk through it one step at a time.
- Script to API: GET /repos?page=1 with token1GET /repos?page=1 with token
- API to Script: 429 Too Many Requests2429 Too Many Requests
- Script to API: Retry after 2 second backoff3Retry after 2 second backoff
- API to Script: 200 OK, items and next link4200 OK, items and next link
- Script to API: GET /repos?page=25GET /repos?page=2
- API to Script: 200 OK, no next link6200 OK, no next link
- 200 OK, 201 Created
- 204 No Content: no body to parse
- Carry on
- 400 bad input, 404 not found
- 401 missing or bad token, 403 not allowed
- Fix the request; only 429 is worth retrying
- 500 a bug on the server
- 502, 503, 504 gateway or overload
- Retry with backoff, then alert
In depth
What one requests call really does
requests.get(url) looks simple, but a lot happens. The hostname is turned into an IP address with DNS. A TCP connection opens, and for https a TLS handshake checks the server's certificate against trusted authorities (requests uses the certifi bundle). Then the request line, headers and body are sent, and the response status, headers and body come back.
requests helps build each part. params={"q": "x"} encodes the query string for you. json={...} sends a JSON body and sets Content-Type: application/json. data={...} sends form fields. On the way back, r.status_code is the number, r.headers is a case-insensitive dict, r.text is the decoded body and r.json() parses JSON.
Never pass verify=False just to silence certificate errors in real automation; it turns off the check that you are talking to the right server. Point verify at your company's CA bundle file instead.
- 1DNS lookup
Hostname to IP address
- 2TCP connect
The connect timeout applies here
- 3TLS handshake
The certificate is checked
- 4Send request
Method, path, headers, body
- 5Read response
The read timeout applies between bytes
- 6Response object
status_code, headers, json()
Timeouts and exceptions
requests has no default timeout. Without one, a server that accepts the connection but never answers can block your script forever. timeout=10 sets both the connect timeout and the read timeout to 10 seconds. A tuple like timeout=(3.05, 30) sets them separately: 3.05 seconds to connect, and up to 30 seconds of silence while reading.
The read timeout is not a limit on the total download time; it is the longest allowed gap between bytes. A slow but steady download can take longer.
Every requests error inherits from requests.exceptions.RequestException. The useful subclasses are ConnectionError (DNS failure, refused connection), Timeout (with ConnectTimeout and ReadTimeout), and HTTPError, which raise_for_status() raises for 4xx and 5xx codes. Catch the specific ones you can handle and let the rest fail loudly.
- ConnectionError
- DNS lookup failed
- Connection refused or reset
- Timeout
- ConnectTimeout (also a ConnectionError)
- ReadTimeout
- HTTPError
- Raised by raise_for_status()
- For 4xx and 5xx responses
- JSONDecodeError
- r.json() on a body that is not JSON
Sessions, auth and secrets
A requests.Session keeps settings and connections between calls. Headers you set on s.headers are sent with every request, and its connection pool reuses open TCP and TLS connections, which can make a script that makes hundreds of calls several times faster.
Auth styles you will meet: auth=("user", "pass") for HTTP Basic, a Bearer token in the Authorization header, and API keys in a custom header such as X-API-Key. Read them from environment variables. os.environ["TOKEN"] fails loudly if the variable is missing, which is better than quietly sending an empty token.
Be careful with logging. Do not log full headers, or URLs that carry keys in the query string. When a call fails, log the status and a short slice of the body, not the request headers. Note also that requests drops the Authorization header when a redirect sends you to a different host, a deliberate safety feature.
Retries with backoff, done right
Retry only what can succeed the second time: connection errors, timeouts, 429 Too Many Requests, and 502, 503 or 504 from a gateway. Do not retry 400, 401, 403 or 404; the request itself is wrong and will fail again.
Wait longer after each failure (exponential backoff), and add a little randomness (jitter) so a hundred clients do not all retry at the same instant. If the server sends a Retry-After header, honour it. urllib3's Retry, mounted on a Session through HTTPAdapter, handles this: it honours Retry-After by default and caps each wait at 120 seconds unless you change backoff_max.
Mind the method. GET, PUT and DELETE are idempotent (repeating them has the same effect as doing them once), so Retry allows them by default, but not POST. A retried POST whose first attempt actually succeeded can create a duplicate. If you must retry POST, use an idempotency key if the API supports one.
- 1Send request
With a timeout
- 2Temporary failure?
Timeout, 429, 502, 503, 504
- 3Wait
Retry-After, or a doubling delay plus jitter
- 4Count attempts
Give up and raise after the limit
- Back to step 1
Pagination and rate limits
APIs split large results in three common ways. Page numbers (?page=3&per_page=100) are simple, but items can shift between pages if data changes while you read. Cursors (?cursor=abc) return a token pointing at the next chunk and stay stable; you stop when the response has no next cursor. Link headers, used by GitHub, put the next URL in a response header, which requests parses into r.links.
Whatever the style, use the largest page size the API allows to cut the number of calls, and put a sanity limit on pages so a bug cannot loop forever.
Rate limits are the other half. Many APIs report your remaining budget in headers. GitHub, for example, sends X-RateLimit-Remaining and X-RateLimit-Reset (a Unix timestamp). A polite script slows down, or sleeps until the reset time, when the remaining count gets low, instead of hammering the API until it answers with 403 or 429.
Learn it in 5 short steps
About 50m each. Track them with a timer in your plan.
- 1Make GET and POST calls with requests~50m
- 2Send auth headers and tokens~50m
- 3Handle status codes and timeouts~50m
- 4Add retries with backoff~50m
- 5Paginate through a public API~50m
Key points
- Always set a timeout; without one, requests can wait forever.
- Call raise_for_status so 4xx and 5xx responses become exceptions.
- Retry only on temporary errors like 429 and 503, with growing delays.
- Keep following the next page until the API says there are no more.
Key terms
Tap a card to flip it. 0/5 known
Examples
import os, requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
s = requests.Session()
s.headers["Authorization"] = f"Bearer {os.environ['GITHUB_TOKEN']}"
retry = Retry(total=5, backoff_factor=1, status_forcelist=[429, 502, 503])
s.mount("https://", HTTPAdapter(max_retries=retry))
url = "https://api.github.com/user/repos?per_page=100"
while url:
r = s.get(url, timeout=10)
r.raise_for_status()
print([repo["name"] for repo in r.json()])
url = r.links.get("next", {}).get("url")Auth, retries with backoff, timeouts and Link-header pagination.
Post a deploy message to a Slack webhook
At the end of a deploy you want a message in the team channel. Step 1: read the incoming webhook URL from an environment variable; the URL itself is the secret. Step 2: POST a small JSON body with json=, which also sets the Content-Type header. Step 3: use a short timeout and raise_for_status. Step 4: if the notification fails, warn but do not fail the deploy. Notice that only the exception's class name is printed: the full error message can contain the webhook URL.
import os, requests
url = os.environ["SLACK_WEBHOOK_URL"]
msg = {"text": "api v1.4.0 deployed to prod"}
try:
r = requests.post(url, json=msg, timeout=(3.05, 10))
r.raise_for_status()
except requests.exceptions.RequestException as e:
# a failed notification must not fail the deploy
print(f"warning: Slack notify failed: {e.__class__.__name__}")A cursor-paginated fetch that respects 429
An internal inventory API returns {"items": [...], "next_cursor": "..."}. Step 1: a generator yields items one by one, so callers can stop early. Step 2: ask for the largest page the API allows. Step 3: on 429, sleep for the Retry-After seconds and try the same page again (this code assumes the header holds seconds; it may also be a date). Step 4: stop when next_cursor is empty. Step 5: the max_pages guard turns a looping bug into a clear error.
import time, requests
def fetch_all(session, url, max_pages=500):
params = {"limit": 100}
for _ in range(max_pages):
r = session.get(url, params=params, timeout=10)
if r.status_code == 429:
time.sleep(int(r.headers.get("Retry-After", "5")))
continue
r.raise_for_status()
body = r.json()
yield from body["items"]
if not body.get("next_cursor"):
return
params["cursor"] = body["next_cursor"]
raise RuntimeError("too many pages, stopping")Quick reference
- requests.get(url, params={...}, timeout=10) encodes the query string for you
- json=payload sends JSON and sets Content-Type: application/json
- timeout=(3.05, 30): 3.05 s to connect, 30 s max silence while reading
- r.raise_for_status() turns 4xx and 5xx responses into requests.HTTPError
- Retry timeouts, 429, 502, 503 and 504; do not retry 400, 401, 403 or 404
- r.links["next"]["url"] follows GitHub-style Link header pagination
- A Session reuses connections and shares headers across many calls
- Do not use verify=False; point verify at your CA bundle instead
Common mistakes
- No timeout, so one hung connection freezes the whole job.
- Retrying non-idempotent POST requests and creating duplicates.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Call https://api.github.com/repos/python/cpython with a 10 second timeout and print the star count and the default branch.
- Exercise 2medium
Write get_json(session, url) that retries up to 4 attempts on ConnectionError, Timeout, or status 429/502/503/504, sleeping about 1, 2, 4 seconds plus random jitter, and raises on anything else.
- Exercise 3hard
List all public repos of a GitHub org, following Link pagination, and print the 5 with the most open issues. If X-RateLimit-Remaining reaches 0, sleep until X-RateLimit-Reset.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Should I use requests or httpx?
- Both are fine. requests is the long-standing standard for synchronous scripts; httpx has a very similar API and adds async support and HTTP/2, which matters inside async apps like FastAPI.
- Why do I get SSLError CERTIFICATE_VERIFY_FAILED?
- The server's certificate is not trusted by the CA bundle requests uses, often because of a company proxy or a private CA. Pass verify="/path/to/ca.pem" or set REQUESTS_CA_BUNDLE, rather than turning verification off.
- How do I upload a file with requests?
- Pass files={"file": open("report.csv", "rb")} to requests.post. requests builds a multipart/form-data body for you.
- What does status 429 mean?
- Too Many Requests: you hit the API's rate limit. Wait, ideally for the time in the Retry-After header, and slow down.