Ollama API: Endpoints, Examples and Error Fixes

Logeshwaran
—

The Ollama API runs on http://localhost:11434 and lets any app use your local models; here are its endpoints, examples and error fixes.

The short version: send a chat request with curl http://localhost:11434/api/chat -d '{"model": "llama3.2", "messages": [{"role": "user", "content": "Hi"}], "stream": false}'. For OpenAI-style code, use the base URL http://localhost:11434/v1 and any API key. No key is needed locally. Connection refused means Ollama isn’t running or isn’t listening where you’re calling from; 404 usually means the model isn’t downloaded yet.

Here’s the part most guides skip: the local Ollama API has no password at all. Anything that can reach port 11434 can use your models, which is exactly why Ollama listens only on 127.0.0.1 until you change it, and why “connection refused” is the most common error people hit.

Jake wanted the shop’s stock script to ask a local model one question every morning: “which parts should I reorder?” The script lives in a Docker container. The first run printed Connection refused.

Jake: "Ollama is running. I can chat with it right there on the screen."

Ethan: "From the PC, yes. The container is a different computer as far as the network is concerned, and Ollama only answers its own machine by default. Two settings fix it."

🧭 NEW HERE? READ THESE FIRST

New to Ollama? These make the rest easier:

Five short reads; the API examples below work with any of these setups.

Ollama API base URL and port

UseOn your computerOllama’s cloud
Native Ollama APIhttp://localhost:11434/apihttps://ollama.com/api
OpenAI-compatible APIhttp://localhost:11434/v1https://ollama.com/v1
Anthropic-compatible clients (base URL)http://localhost:11434https://ollama.com
AuthenticationNoneAPI key (Bearer header)

The port is 11434 (Ollama API base URLs), and by default Ollama binds to 127.0.0.1, so only the same computer can connect. The API isn’t strictly versioned, but Ollama keeps it stable and backwards compatible, so code you write today keeps working.

Ollama API endpoints

EndpointWhat it does
POST /api/chatChat with a list of messages; supports tools and images
POST /api/generateComplete a single prompt
POST /api/embedTurn text into embeddings for search
GET /api/tagsList downloaded models (same as ollama list)
GET /api/psModels loaded in memory right now
POST /api/showDetails of one model
POST /api/pullDownload a model
DELETE /api/deleteDelete a model
POST /api/create, /api/copy, /api/pushBuild, copy and publish models
GET /api/versionOllama version; the quickest “is it running?” test

Ollama API examples

Chat with curl

curl http://localhost:11434/api/chat -d '{
  "model": "llama3.2",
  "messages": [{"role": "user", "content": "Which phone parts fail most often?"}],
  "stream": false
}'

The answer is in message.content. Without "stream": false you get many small JSON objects as the model writes, because streaming is on by default.

Generate with Python

import requests

r = requests.post("http://localhost:11434/api/generate", json={
    "model": "llama3.2",
    "prompt": "Write a one-line reorder reminder for 3 iPhone 15 screens.",
    "stream": False,
})
r.raise_for_status()
print(r.json()["response"])

List your models

curl http://localhost:11434/api/tags

Durations in the responses are in nanoseconds, and the final object of a stream carries the token counts and timings, handy for measuring speed.

Jake: "Which one should my script use, generate or chat?"

Ethan: "Chat. It keeps roles separate, so you can add a system message like “answer with part names only”, and it’s the one that supports tools."

OpenAI-compatible Ollama API

Existing OpenAI code works with a two-line change. The compatibility page notes that the API key field is “required but ignored” locally:

from openai import OpenAI

client = OpenAI(base_url="http://localhost:11434/v1/", api_key="ollama")
reply = client.chat.completions.create(
    model="llama3.2",
    messages=[{"role": "user", "content": "Say this is a test"}],
)
print(reply.choices[0].message.content)

Chat completions, streaming, JSON mode, tools, vision, thinking control, /v1/models and /v1/embeddings are supported, so most OpenAI-based tools can point at Ollama.

Official Ollama libraries for Python and JavaScript

Instead of raw HTTP you can use Ollama’s own libraries, which wrap the same API and work with a local server or the cloud. Python:

# pip install ollama
from ollama import chat

response = chat(
    model="llama3.2",
    messages=[{"role": "user", "content": "Which phone parts fail most often?"}],
)
print(response.message.content)

JavaScript (Node.js):

// npm i ollama
import ollama from 'ollama'

const response = await ollama.chat({
  model: 'llama3.2',
  messages: [{ role: 'user', content: 'Which phone parts fail most often?' }],
})
console.log(response.message.content)

Both default to http://localhost:11434, so they hit the same “connection refused” problems below when Ollama isn’t reachable.

Tool calling with the Ollama API

Tool calling lets the model ask your code to run a function, which is how it reads live data instead of guessing. You describe each function in a tools list; a model with the tools capability (see our Ollama models list) answers with a tool_calls entry naming the function and its arguments. Your code runs it and sends the result back as a message with the role tool.

curl http://localhost:11434/api/chat -d '{
  "model": "qwen3:8b",
  "messages": [{"role": "user", "content": "How many iPhone 15 screens are in stock?"}],
  "tools": [{
    "type": "function",
    "function": {
      "name": "check_stock",
      "description": "Return how many of a part are in stock",
      "parameters": {
        "type": "object",
        "properties": {"part": {"type": "string"}},
        "required": ["part"]
      }
    }
  }],
  "stream": false
}'

The reply’s message.tool_calls contains {"function": {"name": "check_stock", "arguments": {"part": "iPhone 15 screen"}}}. Run that function, append its result, and call /api/chat again for the final answer. For tools you want to share across many apps, an MCP server is the reusable version of the same idea.

Does the Ollama API need an API key?

Not locally: the authentication docs state that the local API at http://localhost:11434 does not require authentication. A key is only for Ollama’s cloud API: create one in your Ollama account, then send it as a Bearer token.

export OLLAMA_API_KEY="your_api_key"
curl https://ollama.com/api/chat \
  -H "Authorization: Bearer $OLLAMA_API_KEY" \
  -d '{"model": "gpt-oss:120b", "messages": [{"role": "user", "content": "Hi"}], "stream": false}'

That’s also why people search for an “Ollama API key” and find nothing locally: there isn’t one to find.

Ollama API connection refused: the fixes

Work through these in order; each one rules out a different cause.

  1. Is Ollama running? Run curl http://localhost:11434/api/version on the same computer. If that fails, open the Ollama app or run ollama serve.
  2. Right address and port? The default is http://localhost:11434. A typo in the port, https instead of http, or a missing /api all look like a dead server.
  3. Calling from another computer? Ollama listens only on 127.0.0.1. Set OLLAMA_HOST=0.0.0.0:11434, restart Ollama, and allow port 11434 in the firewall for your local network only.
  4. Calling from Docker? Inside a container, localhost is the container itself. Use http://host.docker.internal:11434; on Linux start the container with --add-host host.docker.internal:host-gateway. If it still refuses, apply step 3 so Ollama listens beyond localhost.
  5. A web page or browser extension calling it? Ollama accepts browser requests from 127.0.0.1 and 0.0.0.0 by default; add other origins with OLLAMA_ORIGINS.

Setting OLLAMA_HOST on each system:

SystemHow
WindowsQuit Ollama from the taskbar, add OLLAMA_HOST as a user environment variable, start Ollama again
Maclaunchctl setenv OLLAMA_HOST "0.0.0.0:11434", then restart the Ollama app
Linux (systemd)sudo systemctl edit ollama, add Environment="OLLAMA_HOST=0.0.0.0:11434" under [Service], then sudo systemctl daemon-reload and sudo systemctl restart ollama

More on host.docker.internal for containers, including the Linux setting.

Jake: "So it was the container all along?"

Ethan: "The container and the default 127.0.0.1. host.docker.internal plus OLLAMA_HOST, and the morning report runs."

Ollama API errors: 400, 401, 404, 429, 500, 502

Errors come back as JSON with an error field, for example {"error": "the model failed to generate a response"}. If something fails mid-stream, the error arrives as an object inside the stream. What each code means:

CodeMeaningUsual fix
400 Bad RequestMissing parameters or invalid JSONValidate the JSON; include model plus prompt or messages
401 UnauthorizedCloud request without a valid keySend Authorization: Bearer with your key (local calls never need one)
404 Not FoundModel doesn’t exist, or wrong pathollama list for the exact name, ollama pull, check /api/...
429 Too Many RequestsRate limit exceededSlow down; applies to the cloud API
500 Internal Server ErrorThe model failed while runningRead the error text and server log; try a smaller model or context
502 Bad GatewayA cloud model couldn’t be reachedRetry later or use a local model

Is it safe to expose the Ollama API?

Treat port 11434 like an open door. Because the local API has no authentication, anyone who reaches it can use your models and your electricity. Keep it on 127.0.0.1 unless you need network access; when you do, allow it only from the machines that need it, and never forward the port from your router to the internet. If you need remote access, put it behind a VPN or a reverse proxy that adds a password.

Jake’s setup, in four steps

  1. Test from the PC: curl http://localhost:11434/api/version.
  2. Set OLLAMA_HOST=0.0.0.0:11434 and restart Ollama, so the container can reach it.
  3. In the container, call http://host.docker.internal:11434/api/chat with "stream": false.
  4. Allow port 11434 only from the local network, and check the script’s answer every morning.

Frequently asked questions

What is the Ollama API URL?

Locally it is http://localhost:11434/api, and the OpenAI-compatible version is http://localhost:11434/v1. Ollama's cloud API lives at https://ollama.com/api and https://ollama.com/v1.

What port does the Ollama API use?

Port 11434. By default Ollama listens only on 127.0.0.1, so other computers and containers can't reach it until you change the OLLAMA_HOST setting.

Does Ollama need an API key?

Not for your own computer: the local API at http://localhost:11434 has no authentication. You only need an API key to call Ollama's cloud API at ollama.com, sent as Authorization: Bearer with your key.

Is the Ollama API free?

Yes when it runs on your computer: there are no fees and no rate limits beyond what your hardware can handle. Ollama's cloud API needs an account and has usage plans.

Is the Ollama API OpenAI compatible?

Yes. Point any OpenAI client at http://localhost:11434/v1 and use any string as the API key; Ollama requires the field but ignores the value. Chat completions, streaming, JSON mode, tools, vision and embeddings are supported.

How do I fix Ollama API connection refused?

Make sure Ollama is running (open the app or run ollama serve) and test with curl http://localhost:11434/api/version. If the request comes from another computer, a Docker container or a VM, set OLLAMA_HOST=0.0.0.0:11434, restart Ollama and allow port 11434 through the firewall for your network only.

Why does the Ollama API return 404?

Usually the model isn't downloaded or its name is misspelled. Run ollama list to see the exact names, or pull it first with ollama pull. A 404 can also mean a wrong path, such as /chat instead of /api/chat.

Why does the Ollama API return 400?

The request itself is wrong: missing parameters or invalid JSON. Check that the body is valid JSON and includes the model and either prompt (for /api/generate) or messages (for /api/chat).

Why does the Ollama API return 500?

The server hit an error while running the model, often because the model couldn't load, for example when it doesn't fit in memory. Read the error text in the response and Ollama's server log, and try a smaller model or shorter context.

Why does the Ollama API return 429?

A rate limit was exceeded. That applies to Ollama's cloud API; your local server has no request limit of its own.

Why does the Ollama API return 401?

You are calling the cloud API at ollama.com without a valid API key. Create a key, set OLLAMA_API_KEY, and send it in the Authorization: Bearer header. The local API never needs one.

How do I list models with the Ollama API?

Send GET http://localhost:11434/api/tags. It returns every downloaded model with its name, size and modification date, the same list ollama list shows. /api/ps shows the models loaded in memory.

What is the difference between /api/generate and /api/chat?

/api/generate takes a single prompt and returns a completion. /api/chat takes a list of messages with roles (system, user, assistant), which is what you want for conversations and tool calling.

Why is my Ollama API response coming in pieces?

Streaming is on by default: the API sends many small JSON objects as the model writes. Add "stream": false to the request body to get one complete JSON object instead.

How do I call the Ollama API from Docker?

Use http://host.docker.internal:11434 instead of localhost. Docker Desktop resolves that name automatically; on Linux start the container with --add-host host.docker.internal:host-gateway, and make Ollama listen beyond localhost with OLLAMA_HOST.

Is it safe to expose the Ollama API on my network?

Only on a network you trust, because the local API has no password: anyone who can reach port 11434 can use your models. Allow the port only from the machines that need it and never open it to the internet.

Revision note. Written November 27, 2026, for the current Ollama API and its official Python and JavaScript libraries. “Better safe than sorry”: open port 11434 only as wide as you need it.

#AI

Related