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.

By OmniAI Editorial · Nov 20, 2026 · 9 min read

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:

APILocal Ollama serverOllama cloud (direct)
Native Ollama APIhttp://localhost:11434/apihttps://ollama.com/api
OpenAI-compatiblehttp://localhost:11434/v1https://ollama.com/v1
Anthropic-compatible (client base URL)http://localhost:11434https://ollama.com

To check the server is running, open http://localhost:11434 in a browser; it replies that Ollama is running.

Ollama API Endpoints

EndpointMethodWhat it does
/api/chatPOSTGenerates the next message in a conversation (supports tools, images, structured output)
/api/generatePOSTGenerates a response to a single prompt
/api/embedPOSTCreates vector embeddings for text
/api/tagsGETLists models you've downloaded
/api/psGETLists models currently loaded in memory
/api/pullPOSTDownloads a model
/api/create, /api/copy, /api/delete, /api/pushvariousCreate, 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.

A grey server unit drawn in ink in the centre with an orange status light, joined by ink lines to six light tags arranged on both sides.
Your app talks to the local Ollama server over HTTP on port 11434.

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 prompt string (plus an optional system prompt) 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:

FieldWhat it does
streamtrue (default) streams chunks; false returns one response
format"json" or a JSON schema, to force structured output
toolsA list of function definitions the model may call
optionsModel settings such as context length (num_ctx), temperature and seed
keep_aliveHow long the model stays loaded in memory after the request (for example "10m", or 0 to unload immediately)
thinkFor models that support it, turns visible reasoning on or off
imagesBase64-encoded images for vision models (inside a message for chat)
logprobsReturns 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.

A grey rounded box drawn in ink, an ink arrow, and a row of seven small light boxes with short ink lines, the last box orange.
Streaming returns the answer as a series of small JSON chunks.

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_PARALLEL and OLLAMA_MAX_LOADED_MODELS.
  • Keep models warm: set keep_alive so a model stays loaded between requests and avoids slow reloads.
  • Check what's loaded: GET /api/ps shows 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

ProblemLikely causeFix
Connection refusedOllama isn't running, or wrong host or portStart Ollama; check the OLLAMA_HOST setting
"model not found"The model hasn't been pulled, or the name is wrongRun ollama pull <model>; check names with /api/tags
Slow first responseThe model is loading into memoryUse keep_alive to keep it loaded
Long prompts cut offContext window is too smallIncrease num_ctx in options
Out-of-memory errorsModel too large for your RAM or VRAMUse a smaller or more quantized model
Invalid JSON in outputNo format constraintUse 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.

All articles

Read next

Language

EnglishEnglish · en TürkçeTurkish · tr DeutschGerman · de العربيةArabic · ar

Account

Enter your email. We’ll send you a sign-in link and a 6-digit code. No password needed.

Sign in

Theme

Language

Show our email address

To keep spam out of our inbox, please confirm your own email first. We will send you a 6-digit code.

We send codes only to these providers: gmail.com, googlemail.com, outlook.com, hotmail.com, live.com, msn.com, proton.me, protonmail.com, pm.me, icloud.com, me.com, mac.com, yahoo.com, aol.com, gmx.de, gmx.net, web.de, t-online.de, yandex.com, omniai.blog