Calling web APIs with requests
Fetch data from a public API, handle errors and save the results.
By Invicly Tech, , in Python Programming from Zero. About 11 minutes to read.
In short
Web APIs return data over HTTP, usually as JSON. The requests library sends a request with parameters and headers, then you check the status, parse the JSON and save or use the result.
Explained simply
An API is a door that a web service opens for programs instead of people. Instead of a web page, it sends back data, usually as JSON. Weather, exchange rates, GitHub repositories and thousands of other services work this way.
To ask an API for data, your program sends an HTTP request to a URL. The server answers with a status code (a number like 200 for OK or 404 for not found), some headers, and a body. The requests library makes this one line of Python.
Networks fail. Servers are slow, keys expire, and you can hit limits on how many calls you may make. A good script sets a timeout, checks the status, catches errors and tells the user clearly what went wrong instead of crashing with a long traceback.
When the data arrives, you turn it into Python dicts with r.json(), pick out the fields you need and save them to a file. Saving lets you work with the data later without calling the API again.
Press Play on a diagram to walk through it one step at a time.
- Your script to requests: get(url, params, timeout=10)1get(url, params, timeout=10)
- requests to API server: GET /forecast?city=Pune2GET /forecast?city=Pune
- API server to requests: 200 OK + JSON body3200 OK + JSON body
- requests to Your script: Response object4Response object
- 5raise_for_status()Your script to Your script: raise_for_status()
- 6data = r.json()Your script to Your script: data = r.json()
- 200 OK: parse the body
- 201 Created: after a POST
- 204 No Content: nothing to parse
- 400: fix the parameters
- 401/403: check the key or permissions
- 404: wrong URL or id
- 429: wait, then retry
- 500: server bug, report or retry later
- 502/503/504: temporary, retry with backoff
- Not your code, but handle it
In depth
What one requests.get() call really does
When you call requests.get(url, params=..., timeout=10), requests first builds the full URL, encoding your params so spaces become %20 or + and special characters are safe. It then looks up the host name with DNS, opens a TCP connection to port 443 for https, and performs a TLS handshake to check the server's certificate. Only then does it send the request line and headers, like GET /forecast?city=Pune HTTP/1.1.
The server replies with a status line, headers and a body. requests wraps it in a Response: r.status_code, r.headers (case-insensitive), r.text (decoded string), r.content (raw bytes) and r.json(). If you make many calls to the same host, use a requests.Session: it keeps the TCP and TLS connection open and reuses it, which can make repeated calls much faster, and it remembers shared headers.
- 1Build URL
Encode params after the ?
- 2DNS lookup
Host name to IP address
- 3TCP + TLS
Connect to 443, verify certificate
- 4Send request
Method, path, headers
- 5Read response
Status, headers, body
- 6Response object
status_code, headers, json()
Query parameters, headers and authentication
params takes a dict and handles encoding. A list value repeats the key: params={"tag": ["a", "b"]} sends tag=a&tag=b. Values that are None are left out, which is handy for optional filters. Print r.url to see the exact URL that was sent.
Headers carry extra information. Accept: application/json asks for JSON. User-Agent identifies your client, and some APIs reject requests without a sensible one. Authentication is usually one of three styles: an API key in a header (often X-API-Key or Authorization: Bearer token), an API key as a query parameter, or HTTP Basic auth with auth=("user", "password"). Read the key from an environment variable with os.environ, so it never lands in Git. For sending data, use json={...} on requests.post, which serialises the dict and sets Content-Type: application/json for you.
- r.url shows the final, encoded URL
- Session().headers.update({...}) sets headers once for every call
- Keys in query strings can end up in server logs; prefer headers
Errors and timeouts in detail
requests has no timeout by default, so a stuck server can hang your script forever. timeout=10 limits the connect step and the wait between bytes of the response; it is not a limit on the total download time. A tuple like timeout=(3.05, 27) sets connect and read separately.
A 404 or 500 is not an exception by itself: the request worked, the server just said no. r.raise_for_status() raises HTTPError for any 4xx or 5xx code. Network problems raise ConnectionError, slow servers raise Timeout, and everything inherits from requests.RequestException, so one except can catch them all. r.json() on a body that is not JSON (for example an HTML error page) raises requests.exceptions.JSONDecodeError. Catch specific errors where you can act differently, such as retrying on Timeout but stopping on 401.
- ConnectionError
- DNS failure
- Connection refused
- Timeout
- ConnectTimeout
- ReadTimeout
- HTTPError
- From raise_for_status()
- 4xx or 5xx status
- JSONDecodeError
- Body is not valid JSON
- TooManyRedirects
Rate limits and retries
Most APIs limit how many calls you may make, for example per minute or per hour. When you go over, the server returns 429 Too Many Requests, often with a Retry-After header saying how many seconds to wait. Many APIs also send headers showing how many calls you have left; read them in r.headers.
Retrying makes sense for temporary failures: timeouts, 429, and 502, 503 or 504. It does not make sense for 400, 401, 403 or 404, which will fail the same way again. Wait longer between each try (exponential backoff: 1, 2, 4 seconds) so you do not hammer a struggling server. requests can do this for you: mount an HTTPAdapter with a urllib3 Retry object on a Session. By default Retry only retries idempotent methods like GET, and it respects Retry-After.
- Retry(total=3, backoff_factor=1, status_forcelist=[429, 500, 502, 503, 504])
- session.mount("https://", HTTPAdapter(max_retries=retry))
- Cache results locally so reruns do not spend your limit
Pagination and saving results
APIs rarely return everything at once. They split results into pages. Common styles are page numbers (?page=2&per_page=50), offsets (?offset=100&limit=50), cursors (the response includes a next_cursor token you send back) and Link headers that hold the URL of the next page; requests parses these into r.links. Loop until there is no next page, and stop after a safe maximum so a bug cannot loop forever.
When saving, write the parsed data with json.dump(data, f, indent=2). Add a small wrapper with when you fetched it and from which URL, so you know later how fresh the file is. Write to a temporary file and rename it over the old one, so a crash halfway never leaves a broken, half-written file.
Learn it in 4 short steps
About 45m each. Track them with a timer in your plan.
- 1Make GET requests with requests~45m
- 2Pass query params and headers~45m
- 3Handle HTTP errors and timeouts~45m
- 4Save API results to JSON~45m
Key points
- Pass query parameters as a dict with params= instead of building URLs by hand.
- Always set timeout=; requests waits forever by default.
- r.raise_for_status() turns 4xx and 5xx responses into exceptions.
- Keep API keys in environment variables, never in your code.
Key terms
Tap a card to flip it. 0/5 known
Examples
import json, os
import requests
url = "https://api.example.com/forecast"
headers = {"Authorization": f"Bearer {os.environ['API_KEY']}"}
try:
r = requests.get(url, params={"city": "Pune"}, headers=headers, timeout=10)
r.raise_for_status()
except requests.RequestException as err:
raise SystemExit(f"Request failed: {err}")
data = r.json()
with open("forecast.json", "w", encoding="utf-8") as f:
json.dump(data, f, indent=2)Fetch every page of GitHub issues
GitHub's REST API returns 30 items per page by default (up to 100 with per_page) and puts the next page's URL in a Link header. Step 1: create a Session with the Accept header GitHub recommends. Step 2: request the first page with params. Step 3: raise on errors, then extend the list. Step 4: follow r.links["next"] until it is missing. Without a token, GitHub allows only 60 requests per hour, so keep max_pages small.
import requests
s = requests.Session()
s.headers.update({"Accept": "application/vnd.github+json"})
url = "https://api.github.com/repos/python/cpython/issues"
params = {"state": "open", "per_page": 100}
issues, max_pages = [], 3
for _ in range(max_pages):
r = s.get(url, params=params, timeout=10)
r.raise_for_status()
issues.extend(r.json())
if "next" not in r.links:
break
url, params = r.links["next"]["url"], None # next URL already has the params
print(len(issues), "issues fetched")A session with automatic retries and a safe save
A daily script calls an exchange-rate API that sometimes returns 503. Step 1: configure Retry for temporary errors with backoff. Step 2: mount it on a Session. Step 3: make the call and handle any final failure with one clear message and a non-zero exit. Step 4: save with a timestamp, writing to a temp file first and then replacing the old file in one step.
import json, datetime as dt
from pathlib import Path
import requests
from requests.adapters import HTTPAdapter
from urllib3.util import Retry
s = requests.Session()
s.mount("https://", HTTPAdapter(max_retries=Retry(total=3, backoff_factor=1, status_forcelist=[429, 500, 502, 503, 504])))
try:
r = s.get("https://api.example.com/rates", params={"base": "EUR"}, timeout=10)
r.raise_for_status()
except requests.RequestException as e:
raise SystemExit(f"Could not fetch rates: {e}")
tmp = Path("rates.json.tmp"); tmp.write_text(json.dumps({"fetched_at": dt.datetime.now(dt.timezone.utc).isoformat(), "data": r.json()}, indent=2))
tmp.replace("rates.json")Quick reference
- pip install requests (it is not in the standard library)
- requests.get(url, params={...}, headers={...}, timeout=10)
- r.raise_for_status() turns 4xx and 5xx into HTTPError
- except requests.RequestException catches every requests error
- timeout=(3.05, 27) sets connect and read timeouts separately
- requests.post(url, json=payload) sends JSON and sets Content-Type
- Retry 429 and 5xx with backoff; never retry 400, 401, 403 or 404
- Read secrets with os.environ["API_KEY"]; never hard-code them
Common mistakes
- No timeout, so the script hangs when the server is slow.
- Calling r.json() without checking the status, then parsing an error page.
- Committing API keys to Git.
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/users/octocat and print the user's name and number of public repos, with a timeout and status check.
- Exercise 2medium
Write fetch_json(url, params) that returns the parsed JSON, or prints a friendly message and returns None on any network error, error status or invalid JSON.
- Exercise 3hard
Write a function that GETs a URL and, on 429, waits for the Retry-After seconds (default 5) and tries again, up to 3 attempts in total.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Is requests built into Python?
- No. Install it with pip install requests inside your virtual environment. The standard library has urllib.request, but it is far less convenient.
- Should I use requests or httpx?
- requests is the classic choice for simple synchronous scripts. httpx has a very similar API and also supports async code and HTTP/2, so it is worth learning once you need those.
- Where should I keep my API key?
- In an environment variable or a .env file that is listed in .gitignore. Read it with os.environ in your code, so the key never appears in your repository.
- Why does r.json() fail even though the request worked?
- The body is not JSON, often an HTML error page or an empty body from a 204. Check r.status_code and r.headers["Content-Type"] before parsing.