Sub topic 9
Calling the REST API with generate and chat
This chapter assumes you can run ollama run from a terminal, that you know basic HTTP and JSON, and that you can read a short Python script. The Ollama server listens on http://localhost:11434. Everything the CLI does goes through this same API.
Two endpoints
Ollama has two main endpoints for text.
/api/generatetakes a singlepromptstring. Use it for one-off completions with no conversation history./api/chattakes amessageslist. Each message has arole(system,user, orassistant) andcontent. Use it for conversations.
Generate
Send a prompt and set "stream": false to get one JSON object back.
curl http://localhost:11434/api/generate -d '{
"model": "llama3.2",
"prompt": "Explain what a context window is in one sentence.",
"stream": false
}'The generated text is in the response field. The object also contains done and timing fields such as total_duration.
Chat
The chat endpoint receives the whole conversation on every call. The server does not remember earlier requests, so your client must keep the history and resend it.
curl http://localhost:11434/api/chat -d '{
"model": "llama3.2",
"messages": [
{"role": "system", "content": "You answer in one short sentence."},
{"role": "user", "content": "What is quantization?"}
]
}'This request omits "stream": false, so the reply arrives as a series of newline-delimited JSON objects. Each one carries a piece of text in message.content. The last object has done set to true. The next chapter covers handling that stream.
Calling from Python
For a single complete reply, disable streaming and read message.content.
import requests
resp = requests.post(
"http://localhost:11434/api/chat",
json={
"model": "llama3.2",
"messages": [{"role": "user", "content": "Why is the sky blue?"}],
"stream": False,
},
timeout=120,
)
resp.raise_for_status()
print(resp.json()["message"]["content"])The timeout matters. The first request after a model is idle has to load it into memory, which can take several seconds. raise_for_status() turns an HTTP error into an exception instead of letting you parse an error body as if it were a reply.
Common errors
| Symptom | Likely cause |
|---|---|
| Connection refused | The server is not running, or it listens on another host or port. |
| HTTP 404 with "model not found" | The model has not been pulled. Run `ollama pull` first. |
| `KeyError: 'message'` | You called `/api/generate` but read the chat field, or the response was an error object. |
| `JSONDecodeError` | Streaming was on, so the body holds several JSON objects instead of one. |
Choosing between them
Use /api/generate for stateless tasks such as summarizing or classifying a single text. Use /api/chat when you need a system prompt or multiple turns. Many programs use chat for everything, because a one-message list works as well as a prompt.
Exercise
Your Python script calls resp.json()["response"] after posting to /api/chat with "stream": false and gets a KeyError. What is wrong, and how do you fix it?
Show answer
The chat endpoint puts the reply in message.content, not in response. The response field belongs to /api/generate. Change the code to resp.json()["message"]["content"], or switch the request to /api/generate with a prompt.
Exercise
You build a chatbot with /api/chat. On the second user message the model has forgotten the first. Why, and what should the client do?
Show answer
The server keeps no conversation state between requests. The client must append each user message and each assistant reply to the messages list and send the full list on every call.