Dev tools
Ollama API: How to Use It, With Examples
How to use the Ollama API: REST endpoints and port, chat and generate examples in curl and Python, streaming, JSON output, tools, embeddings and API keys.
The Ollama API is a REST API that Ollama runs on your computer at http://localhost:11434, letting any program send prompts to local models and get responses back as JSON. The two main endpoints are /api/chat for conversations and /api/generate for single prompts, plus endpoints for embeddings and for listing, pulling and managing models. Local requests need no API key. Ollama also offers OpenAI- and Anthropic-compatible endpoints, so many existing tools work by just changing the base URL, and the same API can call Ollama's cloud models at https://ollama.com/api with an API key.
This guide shows how to use the Ollama API step by step, with curl and Python examples for chat, generation, streaming, structured JSON output, tool calling and embeddings, plus settings, remote access and common errors. If you haven't installed Ollama yet, our guide on how to run an LLM locally covers setup.
What Is the Ollama REST API?
When the Ollama app or ollama serve is running, it starts an HTTP server. The Ollama REST API exposes everything the command line can do: run models, chat, create embeddings, pull and delete models, and see what's loaded. Applications such as chat interfaces, coding assistants and agent frameworks use it to talk to local models.
Ollama API port and base URLs
The default Ollama API port is 11434. The base URLs, from Ollama's documentation:
| API | Local Ollama server | Ollama cloud (direct) |
|---|---|---|
| Native Ollama API | http://localhost:11434/api | https://ollama.com/api |
| OpenAI-compatible | http://localhost:11434/v1 | https://ollama.com/v1 |
| Anthropic-compatible (client base URL) | http://localhost:11434 | https://ollama.com |
To check the server is running, open http://localhost:11434 in a browser; it replies that Ollama is running.
Ollama API Endpoints
| Endpoint | Method | What it does |
|---|---|---|
/api/chat | POST | Generates the next message in a conversation (supports tools, images, structured output) |
/api/generate | POST | Generates a response to a single prompt |
/api/embed | POST | Creates vector embeddings for text |
/api/tags | GET | Lists models you've downloaded |
/api/ps | GET | Lists models currently loaded in memory |
/api/pull | POST | Downloads a model |
/api/create, /api/copy, /api/delete, /api/push | various | Create, copy, delete and publish models |
Streaming responses use newline-delimited JSON: one JSON object per chunk, with "done": true on the last one.
Ollama API Example: Chat With curl
First pull a model, for example ollama pull gemma4. Then send a chat request:
curl http://localhost:11434/api/chat -d '{
"model": "gemma4",
"messages": [
{"role": "system", "content": "You are a concise assistant."},
{"role": "user", "content": "Explain what an embedding is in two sentences."}
],
"stream": false
}'With "stream": false, you get one JSON object back, with the reply in message.content, plus timing and token counts. Without it, the API streams chunks as they're generated.
The messages array works like other chat APIs: roles are system, user, assistant and tool. To continue a conversation, send the whole history each time; the server doesn't remember previous requests.
Chat vs Generate
- `/api/chat` takes a list of messages and is the right choice for most applications, including assistants, agents and anything with tools or images.
- `/api/generate` takes a single
promptstring (plus an optionalsystemprompt) and suits one-shot tasks such as summarizing a text or classifying a sentence.
curl http://localhost:11434/api/generate -d '{
"model": "gemma4",
"prompt": "Write a one-line summary of the water cycle.",
"stream": false
}'Ollama API Example in Python
You can call the REST API with any HTTP library, but the official Python library is simpler. Here's an Ollama API example Python developers can copy. Install it with pip install ollama:
from ollama import chat
response = chat(
model="gemma4",
messages=[{"role": "user", "content": "Why is the sky blue?"}],
)
print(response.message.content)To stream the answer as it's generated:
from ollama import chat
stream = chat(
model="gemma4",
messages=[{"role": "user", "content": "Why is the sky blue?"}],
stream=True,
)
for chunk in stream:
print(chunk["message"]["content"], end="", flush=True)There's also an official JavaScript library (npm install ollama) with the same shape. And because Ollama has an OpenAI-compatible endpoint, you can use the OpenAI SDK by pointing it at http://localhost:11434/v1; most tools that accept a custom OpenAI base URL work this way.
Useful Request Options
The chat and generate endpoints accept several optional fields:
| Field | What it does |
|---|---|
stream | true (default) streams chunks; false returns one response |
format | "json" or a JSON schema, to force structured output |
tools | A list of function definitions the model may call |
options | Model settings such as context length (num_ctx), temperature and seed |
keep_alive | How long the model stays loaded in memory after the request (for example "10m", or 0 to unload immediately) |
think | For models that support it, turns visible reasoning on or off |
images | Base64-encoded images for vision models (inside a message for chat) |
logprobs | Returns log probabilities of output tokens |
The default context length can be smaller than a model's maximum, so if long prompts get cut off, increase num_ctx in options, keeping in mind that a larger context uses more memory.
Structured JSON Output
To get reliable JSON, pass a JSON schema in format. In Python, a Pydantic model works well:
from ollama import chat
from pydantic import BaseModel
class Product(BaseModel):
name: str
price: float
in_stock: bool
response = chat(
model="gemma4",
messages=[{"role": "user", "content": "Extract: Blue mug, 12.50 dollars, available now."}],
format=Product.model_json_schema(),
)
product = Product.model_validate_json(response.message.content)
print(product)The model's output is constrained to the schema, which makes it easy to parse and validate.
Tool Calling
Models that support tools can ask your program to run a function. You describe the function in tools; if the model wants to use it, the response contains tool_calls instead of a final answer. Your code runs the function, adds the result as a message with the tool role, and calls the API again so the model can finish its answer. This loop is the basis of agents built on local models; check that the model you choose is marked as supporting tools in Ollama's library.
Embeddings
For search and retrieval-augmented generation, create embeddings with an embedding model:
curl http://localhost:11434/api/embed -d '{
"model": "embeddinggemma",
"input": ["Ollama runs models locally.", "The API listens on port 11434."]
}'The response contains one vector per input string, which you can store in a vector database or compare with cosine similarity.
Native API vs OpenAI-Compatible Endpoint
Should you use Ollama's native /api endpoints or the OpenAI-compatible /v1 endpoints? Use the OpenAI-compatible endpoint when you want portability: code written for the OpenAI SDK can switch between local models and hosted providers by changing the base URL and model name. Use the native API when you want Ollama-specific features, such as model management, keep_alive, detailed model options and the full set of response fields. Many applications use the compatible endpoint for chat and the native API for managing models.
Ollama API Key and Cloud Models
Do you need an Ollama API key? Not for local use: the local API at http://localhost:11434 doesn't require authentication. You need an API key only to call Ollama's cloud models directly at https://ollama.com/api (or /v1), which run larger models on Ollama's servers. Create a key in your Ollama account settings, set it as OLLAMA_API_KEY, and send it in an Authorization: Bearer header. Alternatively, sign in to Ollama from your terminal and call cloud models through your local server. Keep keys out of browser code and source control.
Accessing the Ollama API From Other Machines
By default, Ollama listens only on localhost, so other computers on your network can't reach it. To serve it to other devices, set the OLLAMA_HOST environment variable (for example to 0.0.0.0:11434) and restart Ollama. Because the local API has no authentication, don't expose it directly to the internet. Put it behind a private network such as a VPN, or a reverse proxy with authentication. Tools like Open WebUI give you a chat interface with user accounts on top of the Ollama API.
Handling Concurrency and Performance
- Parallel requests: Ollama can process several requests at once and keep more than one model loaded, controlled by environment variables such as
OLLAMA_NUM_PARALLELandOLLAMA_MAX_LOADED_MODELS. - Keep models warm: set
keep_aliveso a model stays loaded between requests and avoids slow reloads. - Check what's loaded:
GET /api/psshows loaded models and how much memory they use. - Heavy production traffic: for many concurrent users on a GPU server, dedicated inference servers like vLLM batch requests more efficiently; our comparison of Ollama vs LM Studio also covers when each local tool fits.
Common Errors and Fixes
| Problem | Likely cause | Fix |
|---|---|---|
| Connection refused | Ollama isn't running, or wrong host or port | Start Ollama; check the OLLAMA_HOST setting |
| "model not found" | The model hasn't been pulled, or the name is wrong | Run ollama pull <model>; check names with /api/tags |
| Slow first response | The model is loading into memory | Use keep_alive to keep it loaded |
| Long prompts cut off | Context window is too small | Increase num_ctx in options |
| Out-of-memory errors | Model too large for your RAM or VRAM | Use a smaller or more quantized model |
| Invalid JSON in output | No format constraint | Use format with a JSON schema |
FAQ
What is the Ollama API?
The Ollama API is a REST API served by Ollama on your machine, by default at http://localhost:11434. Applications use it to chat with local models, generate text, create embeddings and manage models.
What port does the Ollama API use?
Port 11434 by default. You can change the host and port with the OLLAMA_HOST environment variable.
Does Ollama need an API key?
Not for local use. An API key is only needed to call Ollama's cloud models directly at https://ollama.com/api or https://ollama.com/v1.
Is the Ollama API compatible with the OpenAI API?
Yes, Ollama provides OpenAI-compatible endpoints at /v1, so tools and SDKs built for OpenAI can use local models by changing the base URL. It also provides an Anthropic-compatible endpoint.
How do I use the Ollama API in Python?
Install the official library with pip install ollama, then call chat() with a model name and a list of messages. You can also use any HTTP library to call the REST endpoints directly.