APIs and HTTP
Be able to call a REST API with requests, interpret status codes and handle keys safely.
Prerequisites
- CPython — files, CSV and JSONrequired
Intuition
Almost every AI service is reached through an HTTP API: you send a request (method + URL + JSON if needed) and get a response (status code + JSON).
| Code | Means | What you do |
|---|---|---|
| 200 | OK | read the response |
| 400 | your request is wrong | read the error message |
| 401/403 | no key, or the wrong one | check the key |
| 404 | wrong address | check the URL |
| 429 | too many calls | wait and try again |
| 500 | the server fell over | try again later |
Keys are passwords. Never in the code, never in git — read them from an environment variable.
Code
import os, requests
KEY = os.environ["LLM_API_KEY"] # set outside the code
r = requests.post(
"https://api.example.com/v1/chat/completions",
headers={"Authorization": f"Bearer {KEY}"},
json={"model": "small", "messages": [{"role": "user", "content": "Hi"}]},
timeout=30,
)
if r.status_code == 429:
print("quota exhausted — wait", r.headers.get("Retry-After"))
r.raise_for_status() # raises on 4xx/5xx
response = r.json()
print(response["choices"][0]["message"]["content"])
Always set a timeout — otherwise the program can hang forever when the server does not answer.
Mastery means
- Calls a REST API with requests and parses the JSON
- Explains the status codes 200/400/401/404/429/500
- Handles keys via environment variables
Sign in to do the exercises and build your mastery up.
Sources
- requests — dokumentation (Apache-2.0) — Apache-2.0
- Wikipedia — HTTP-statuskoder (CC BY-SA 4.0) — CC BY-SA 4.0