Calling APIs with requests
Talk to REST APIs from Python — auth, JSON, status checks, and error handling.
Most automation eventually calls a REST API — a cloud provider, a CI system, a
webhook. The requests library makes HTTP simple:
requests.get/post/put/delete(url, ...)for the verbsparams=for query strings,json=for a JSON body,headers=for auth.status_code,.json(), and.raise_for_status()to handle responses
Always check the status and handle failures. raise_for_status() turns a 4xx/5xx
into an exception so errors don’t pass silently. Read secrets (tokens) from the
environment, never hardcode them.
import os, requests
token = os.environ["API_TOKEN"] # from the environment
headers = {"Authorization": f"Bearer {token}"}
resp = requests.get(
"https://api.example.com/v1/servers",
headers=headers,
params={"status": "running"},
timeout=10,
)
resp.raise_for_status() # raise on 4xx/5xx
for server in resp.json()["items"]:
print(server["name"])
# Create a resource
requests.post("https://api.example.com/v1/tags",
json={"name": "prod"}, headers=headers, timeout=10) - GET a public JSON API (e.g. a weather or quotes API) and print one field.
- Add
raise_for_status()and trigger it by hitting a 404 URL. - Read an API token from an environment variable instead of hardcoding it.
- Add a
timeoutand explain what happens without one.
Cheat Sheet▾
| Task | Code |
|---|---|
| GET | requests.get(url, timeout=10) |
| POST JSON | requests.post(url, json=body) |
| Query params | params={"k": "v"} |
| Auth header | headers={"Authorization": "Bearer …"} |
| Status code | resp.status_code |
| Parse JSON body | resp.json() |
| Raise on error | resp.raise_for_status() |
Common Interview Questions▾
How do you handle an unsuccessful HTTP response with requests?
Check resp.status_code or call resp.raise_for_status(), which raises an
exception for 4xx/5xx so failures aren’t silently ignored.
Where should API tokens come from in a script?
From the environment or a secrets manager — never hardcoded in source, which would leak them into version control.
Why always set a timeout on requests?
Without a timeout, a slow or hung server can block your script forever; a timeout fails fast so you can retry or error out.