← Master Index
Vol. 03 Module 3.4 Lecture

Calling REST APIs (requests)

Essential Python Skills for AI Engineers (added — needed in practice, not in original outline)

How This Lesson Fits the Module

Modern AI applications are rarely standalone scripts. They call embedding APIs, LLM endpoints, vector databases, and labeling services over HTTP. The requests library is the standard way to make REST calls from Python—simpler than raw sockets and sufficient for most inference gateways and data ingestion tasks.

Combined with environment variables for API keys, this lecture bridges local Python skills to production integrations.

Learning Objectives

By the end of this lesson, students should be able to:

  • Make GET and POST requests with the requests library.
  • Pass query parameters, JSON bodies, and headers including authentication.
  • Inspect status codes and parse JSON responses safely.
  • Set timeouts and handle connection errors with try/except.
  • Understand REST verbs (GET, POST, PUT, DELETE) at a practical level.
  • Structure API client code for testability and reuse.

Introduction: HTTP from Python

REST (Representational State Transfer) APIs expose resources over HTTP. Clients send verbs to URLs; servers return status codes and JSON payloads. The requests library wraps this in a few lines of Python.

import os
import requests

API_KEY = os.environ["OPENAI_API_KEY"]
BASE = "https://api.openai.com/v1"

resp = requests.post(
    f"{BASE}/chat/completions",
    headers={"Authorization": f"Bearer {API_KEY}"},
    json={
        "model": "gpt-4o-mini",
        "messages": [{"role": "user", "content": "Summarize RAG in one sentence."}],
    },
    timeout=60,
)
resp.raise_for_status()
data = resp.json()
print(data["choices"][0]["message"]["content"])
MethodTypical Userequests Call
GETFetch resource / searchrequests.get(url, params={...})
POSTCreate / invoke modelrequests.post(url, json={...})
PUTReplace resourcerequests.put(url, json={...})
DELETERemove resourcerequests.delete(url)

Status Codes and Error Handling

Common HTTP Status Codes
  • 200 OK — success
  • 400 Bad Request — client sent invalid payload
  • 401 Unauthorized — missing or invalid API key
  • 429 Too Many Requests — rate limited; backoff and retry
  • 500 Internal Server Error — server-side failure
try:
    resp = requests.get(url, timeout=10)
    resp.raise_for_status()
except requests.HTTPError:
    print("Bad status:", resp.status_code, resp.text)
except requests.RequestException as exc:
    print("Network error:", exc)
Common Misconception:requests raises on 404 or 500 automatically.”

Reality: requests returns a response object for any HTTP status. Call resp.raise_for_status() or check resp.status_code explicitly.

Knowledge Check

  1. Short Answer: How do you send JSON in a POST body? Answer: requests.post(url, json=payload).
  2. True/False: Always set a timeout on production API calls. Answer: True.
  3. Multiple Choice: HTTP 401 usually means: (a) server down, (b) auth failure, (c) success, (d) rate limit. Answer: (b).
  4. Short Answer: How do you pass query parameters on a GET? Answer: requests.get(url, params={...}).
  5. True/False: requests automatically raises on HTTP 404 or 500. Answer: False—call raise_for_status() or check status_code.
  6. Short Answer: What does HTTP 429 mean for an LLM API? Answer: Too Many Requests—you are rate limited; backoff and retry.
  7. Multiple Choice: Typical verb to invoke a model endpoint: (a) GET only, (b) POST, (c) DELETE, (d) TRACE. Answer: (b).
  8. True/False: Store API keys in source files rather than environment variables. Answer: False—load secrets from the environment.
  9. Short Answer: How do you parse a JSON response body? Answer: resp.json() after a successful request.
  10. Multiple Choice: Network failures (DNS, timeout) are typically caught as: (a) requests.RequestException, (b) SyntaxError, (c) IndentationError, (d) StopIteration. Answer: (a).

Key Takeaways

  • requests is the standard HTTP client for Python AI integrations.
  • Use json= for bodies, headers= for auth, timeout= for safety.
  • Check status codes and handle network failures explicitly.
  • Next: Environment Variables to manage API keys securely.
Trainer’s Guide

Mock server exercise: Use httpbin.org for safe GET/POST practice before students touch paid LLM APIs.

Recap: requests is the standard HTTP client for AI integrations; next, keep keys out of source with Environment Variables (.env).