Calling APIs with requests

💤0
Lv 10 XP
← ⚙️ Scripting & Automation · Python

Calling APIs with requests

Intermediate ⭐ 80 XP ⏱ 18 min #python#api#http#requests

Talk to REST APIs from Python — auth, JSON, status checks, and error handling.

📖Theory

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 verbs
  • params= 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.

🌍Real-World Example
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)
✍️Hands-On Exercise
  1. GET a public JSON API (e.g. a weather or quotes API) and print one field.
  2. Add raise_for_status() and trigger it by hitting a 404 URL.
  3. Read an API token from an environment variable instead of hardcoding it.
  4. Add a timeout and explain what happens without one.
🧾Cheat Sheet
TaskCode
GETrequests.get(url, timeout=10)
POST JSONrequests.post(url, json=body)
Query paramsparams={"k": "v"}
Auth headerheaders={"Authorization": "Bearer …"}
Status coderesp.status_code
Parse JSON bodyresp.json()
Raise on errorresp.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.

📚Official Documentation

📝 My notes on this topic

Auto-saves as you type