Skip to content
AI-grafen
DAI developerProgramming· about 45 min· fundamentals that rarely change· verified 2026-09-20· EN

APIs and HTTP

Be able to call a REST API with requests, interpret status codes and handle keys safely.

Prerequisites

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).

CodeMeansWhat you do
200OKread the response
400your request is wrongread the error message
401/403no key, or the wrong onecheck the key
404wrong addresscheck the URL
429too many callswait and try again
500the server fell overtry 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

All the sources and licences