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
requestslibrary. - 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"])
| Method | Typical Use | requests Call |
|---|---|---|
| GET | Fetch resource / search | requests.get(url, params={...}) |
| POST | Create / invoke model | requests.post(url, json={...}) |
| PUT | Replace resource | requests.put(url, json={...}) |
| DELETE | Remove resource | requests.delete(url) |
Status Codes and Error Handling
- 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)
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
- Short Answer: How do you send JSON in a POST body? Answer:
requests.post(url, json=payload). - True/False: Always set a
timeouton production API calls. Answer: True. - Multiple Choice: HTTP 401 usually means: (a) server down, (b) auth failure, (c) success, (d) rate limit. Answer: (b).
- Short Answer: How do you pass query parameters on a GET? Answer:
requests.get(url, params={...}). - True/False:
requestsautomatically raises on HTTP 404 or 500. Answer: False—callraise_for_status()or checkstatus_code. - Short Answer: What does HTTP 429 mean for an LLM API? Answer: Too Many Requests—you are rate limited; backoff and retry.
- Multiple Choice: Typical verb to invoke a model endpoint: (a) GET only, (b) POST, (c) DELETE, (d) TRACE. Answer: (b).
- True/False: Store API keys in source files rather than environment variables. Answer: False—load secrets from the environment.
- Short Answer: How do you parse a JSON response body? Answer:
resp.json()after a successful request. - Multiple Choice: Network failures (DNS, timeout) are typically caught as: (a)
requests.RequestException, (b)SyntaxError, (c)IndentationError, (d)StopIteration. Answer: (a).
Key Takeaways
requestsis 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.
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).