HTTP Requests And JSON
- Always pass a
timeout, callresponse.raise_for_status(), and check keys afterresponse.json()—otherwise a slow or failing API hangs your script or crashes with a confusingKeyError.
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(): A404or500error page still returns aResponseobject—calling.json()on an HTML error page raisesJSONDecodeErrorinstead of showing the HTTP status. - Hardcoded
localhost:http://localhost:11434works 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.