--- HTTP Requests And JSON • Python Cabinet

HTTP Requests And JSON

  • Always pass a timeout, call response.raise_for_status(), and check keys after response.json()—otherwise a slow or failing API hangs your script or crashes with a confusing KeyError.

How it works

requests.post() sends Python dicts as JSON automatically when you use json=payload (it also sets Content-Type: application/json for you). It returns a Response object, not a dict—call .json() to parse the body:

import requests

response = requests.post(
    "http://localhost:11434/api/embed",
    json={"model": "nomic-embed-text", "input": text},
    timeout=120,
)
response.raise_for_status()
vector = response.json()["embeddings"][0]

What can go wrong

  • No timeout = infinite hang: Without timeout=..., a stalled server can freeze your script indefinitely.
  • Skipping raise_for_status(): A 404 or 500 error page still returns a Response object—calling .json() on an HTML error page raises JSONDecodeError instead of showing the HTTP status.
  • Hardcoded localhost: http://localhost:11434 works locally, not inside a deployed container unless configured via environment variable.

Referenced code

From app/semantic_retrieval.py and app/ollama_client.py in ai-security-lab:

def generate_embedding(text: str) -> list[float]:
    url = "http://localhost:11434/api/embed"
    payload = {"model": "nomic-embed-text", "input": text}
    response = requests.post(url, json=payload, timeout=120)
    response.raise_for_status()
    result = response.json()
    return result["embeddings"][0]

Evidence: app/semantic_retrieval.py, app/ollama_client.py, and app/main.py in ai-security-lab. Related: Local Ollama chat over HTTP and FastAPI request and response boundaries.