Intermediate 12 minDaily plan

Open WebUI API: using it with Python

BestLLMfor — Open WebUI — API with Python

The Open WebUI API lets you call the same models, assistants, and access rights as the web interface from a Python script, using a personal key instead of a password. This guide covers creating the key, admin-side permissions, a complete chat request, how to read 401 and 403 errors, and above all how to choose between the Open WebUI API and the direct Ollama API, which don't serve the same need. The endpoints come from the API Endpoints page of the official documentation, accessed on 30/10/2026; the procedure was not re-run for this guide, and the examples use only fictitious data.

By Mohamed Meguedmi·Update 2026-12-05·Tested on Windows, macOS, and Linux

#Open WebUI API or direct Ollama API: which one should you call?

In the most common stack, Ollama runs the model and listens on http://localhost:11434, while Open WebUI, installed on top, provides the UI, accounts, documents, and assistants. Both expose an HTTP API, and a Python script can talk to either one. The difference isn't the model, which is the same, but everything around it.

Direct Ollama API (port 11434)
/api/chat, /api/generate, and /api/tags endpoints, plus an OpenAI-compatible layer under /v1. No built-in authentication: anyone who can reach the port can use every model. No accounts, no Open WebUI assistants, no knowledge bases. It's the shortest path for a personal script on the machine hosting Ollama.
Open WebUI API (UI port, often 3000)
/api/models and /api/chat/completions endpoints (OpenAI-compatible format), plus a proxy to Ollama under /ollama/. Each request carries a key tied to an account: model access permissions, custom assistants, and knowledge bases apply just as they do in the interface.
When to prefer Open WebUI
Several people share the machine, you want to call an assistant created in the workspace or query a knowledge base, or you don't want to open the Ollama port on the network.
When to prefer Ollama directly
Local single-user script, need for Ollama-specific options (keep_alive, structured JSON output, embeddings), or no Open WebUI. Our guide to the Ollama REST API with Python covers this case.
i
What this guide doesn't claim
No model responses, screenshots, or latency measurements are presented as observed. The API paths are taken from docs.openwebui.com/reference/api-endpoints, accessed on 30/10/2026. Open WebUI evolves quickly: check your version (Settings, About) and reread that page before putting a script into production.

#Prerequisites

The complete kit for building your own AI assistant.

Benefit from our experience and a guided path to build your local assistant and use your AI every day.

  • Lifetime online access
  • PDF + files
  • Refunded within 30 days
Open WebUI reachable
An instance installed and connected to Ollama. The examples assume http://localhost:3000, the address used by the most common Docker installation (-p 3000:8080); adjust if your instance runs elsewhere.
A model visible in the UI
At least one Ollama model downloaded and selectable in the chat, for example qwen3.5:9b. At Q4_K_M, a 7B model needs about 5 GB of VRAM and a 14B about 9 GB; using the API doesn't change these requirements.
Python 3 and requests
A virtual environment with the requests library. The openai package is optional (step 5).
A user account
The account the script will act as. Avoid using the admin account for a script: create a dedicated account with only the access it needs.
Terminal — Python environment
python3 -m venv .venv
source .venv/bin/activate
pip install requests

# Vérifier qu'Open WebUI répond (adapter l'adresse)
curl -s -o /dev/null -w "%{http_code}\n" http://localhost:3000/

#Step 1: Create a Open WebUI API key and set permissions

Open WebUI accepts two types of token in the Authorization: Bearer header: the session token (JWT) obtained at sign-in, and an API key generated from your account. For a script, the API key is the right choice: you can revoke it without changing your password, and it doesn't depend on a browser session.

  1. 01
    Admin side: allow keys
    In the admin panel, under Settings then General, the option to enable API keys must be turned on (the ENABLE_API_KEY environment variable in the configuration documentation). Depending on the version, non-admin users also need a dedicated permission, granted by default or per group under Users then Groups. Without it, the create button doesn't appear in their account.
  2. 02
    Optional: restrict endpoints
    The configuration documentation describes a way to restrict which endpoints a key can access (ENABLE_API_KEY_ENDPOINT_RESTRICTIONS and API_KEY_ALLOWED_ENDPOINTS). For a chat-only script, allowing only /api/models and /api/chat/completions limits the damage if the key leaks. Check the exact names on the Environment Variables page for your version.
  3. 03
    User side: generate the key
    Signed in with the dedicated account, open Settings, then Account, API Keys section, and create the key. It usually starts with sk-. Copy it immediately into your secrets manager: don't paste it into a ticket, a chat, or your code.
  4. 04
    Check model access
    The key acts with its owner's permissions. If a model or assistant is restricted to a group, the script's account must belong to that group; otherwise it won't appear in /api/models and calls will fail.
!
A key is as good as an account
Anyone who obtains the key can use the instance on its owner's behalf, including querying their knowledge bases. An admin key potentially grants access to admin endpoints. Never commit it to version control, never put it in a URL, and revoke it from the same screen at the slightest doubt.

#Step 2: keep the key out of your code

The script reads the key from an environment variable. For local use, a .env file excluded from the repository is enough; on a server, prefer your orchestrator's secrets mechanism (a systemd environment file readable only by the service user, a Docker secret, etc.).

Terminal — environment variables (dummy values)
# Saisie sans écho, pour ne pas laisser la clé dans l'historique du shell
read -rs OPENWEBUI_API_KEY && export OPENWEBUI_API_KEY
export OPENWEBUI_URL="http://localhost:3000"

# Si vous utilisez un fichier .env, excluez-le du dépôt
echo ".env" >> .gitignore

Avoid echo $OPENWEBUI_API_KEY to "check" it: the value ends up in the terminal, and sometimes in logs. The script below only shows whether the key is present, never its contents.

#Step 3: list accessible models

GET /api/models returns the models the account can use: Ollama models, OpenAI-compatible connections, and workspace assistants. It's the best first call, because it validates the address, the key, and the permissions all at once. The ID to reuse in chat requests is the id field of each entry.

lister_modeles.py
import os
import sys
import requests

BASE_URL = os.environ.get('OPENWEBUI_URL', 'http://localhost:3000')
API_KEY = os.environ.get('OPENWEBUI_API_KEY')

if not API_KEY:
    sys.exit('OPENWEBUI_API_KEY absente : définissez-la avant de lancer le script.')

HEADERS = {'Authorization': f'Bearer {API_KEY}'}

resp = requests.get(f'{BASE_URL}/api/models', headers=HEADERS, timeout=30)
if resp.status_code != 200:
    # On affiche le code et le message, jamais les en-têtes envoyés
    sys.exit(f'Erreur {resp.status_code} : {resp.text[:300]}')

data = resp.json()
# La réponse suit le format OpenAI : une liste sous la clé 'data'
for model in data.get('data', []):
    print(model.get('id'), '|', model.get('name'))

If the list is empty even though the interface shows models, the script's account doesn't have the same permissions as your usual account: compare the two accounts' groups instead of looking for a network problem.

#Step 4: send a chat request to the Open WebUI API in Python

POST /api/chat/completions accepts a body in the OpenAI Chat Completions API format: a model field (the id obtained in step 3) and a messages list with system, user, and assistant roles. If model refers to a workspace assistant, Open WebUI applies its system prompt, parameters, and sources before forwarding the request to the base model.

chat_open_webui.py
import os
import sys
import requests

BASE_URL = os.environ.get('OPENWEBUI_URL', 'http://localhost:3000')
API_KEY = os.environ.get('OPENWEBUI_API_KEY')
MODEL = os.environ.get('OPENWEBUI_MODEL', 'qwen3.5:9b')  # id lu dans /api/models

if not API_KEY:
    sys.exit('OPENWEBUI_API_KEY absente.')

# Données de test fictives : aucune information réelle
note_fictive = (
    'Réunion du 12/03 (exemple fictif) : Alice livre la maquette vendredi, '
    'Bruno relance le fournisseur Exemple SARL, budget à confirmer.'
)

payload = {
    'model': MODEL,
    'messages': [
        {'role': 'system', 'content': 'Tu extrais les actions sous forme de liste : qui, quoi, quand.'},
        {'role': 'user', 'content': note_fictive},
    ],
    'stream': False,
}

resp = requests.post(
    f'{BASE_URL}/api/chat/completions',
    headers={'Authorization': f'Bearer {API_KEY}', 'Content-Type': 'application/json'},
    json=payload,
    timeout=300,  # le premier appel peut inclure le chargement du modèle
)

if resp.status_code != 200:
    sys.exit(f'Erreur {resp.status_code} : {resp.text[:300]}')

reponse = resp.json()
print(reponse['choices'][0]['message']['content'])
generous timeout
If the model isn't in memory, Ollama must load it first. The delay depends on the model and the disk; a timeout that's too short causes a client-side error while the server is still working.
stream: False
The response arrives all at once, in OpenAI format: the text is in choices[0].message.content. Easier to handle in a batch script.
Multi-turn conversation
The API doesn't keep the history for you: send the full list of messages with every call, including previous replies with the assistant role.
History in the interface
The documentation doesn't describe a call to /api/chat/completions as a conversation saved in the sidebar. Don't rely on the UI to find these exchanges later; log on the script side if needed, without writing sensitive data.

The same documentation page describes querying a file or a knowledge base: you add a files field to the body containing {type: 'file', id: ...} or {type: 'collection', id: ...} objects, after uploading the file via /api/v1/files/ or creating the knowledge base in the workspace. It works on the RAG principle: only excerpts are inserted into the context. Test with a dummy document first and make sure the script's account actually has access to the knowledge base.

Request body with a knowledge base (excerpt)
payload = {
    'model': MODEL,
    'messages': [{'role': 'user', 'content': 'Quel est le délai de réponse prévu ?'}],
    # id de la base, visible dans son URL de l'espace de travail
    'files': [{'type': 'collection', 'id': 'ID-DE-LA-BASE'}],
}

#Step 5: streaming and the OpenAI client

With 'stream': True, the response arrives in chunks in OpenAI's Server-Sent Events format: lines prefixed with data:, each carrying a piece of text in choices[0].delta.content, followed by a data: [DONE] line. This is useful for displaying text as it's generated in an interactive tool.

Streaming with requests
import json

payload['stream'] = True
with requests.post(
    f'{BASE_URL}/api/chat/completions',
    headers={'Authorization': f'Bearer {API_KEY}'},
    json=payload,
    stream=True,
    timeout=300,
) as resp:
    resp.raise_for_status()
    for line in resp.iter_lines(decode_unicode=True):
        if not line or not line.startswith('data: '):
            continue
        chunk = line[len('data: '):]
        if chunk == '[DONE]':
            break
        delta = json.loads(chunk)['choices'][0].get('delta', {})
        print(delta.get('content', ''), end='', flush=True)
print()

Because the endpoint follows the OpenAI format, the official openai SDK should in principle work as a client: it appends /chat/completions to the base URL itself, so you point that URL at /api. This compatibility follows from the documented format, not from a test run for this guide; if you need a Open WebUI-specific field (such as files), pass it via extra_body or fall back to requests.

Variant using the openai SDK (pip install openai)
import os
from openai import OpenAI

client = OpenAI(
    base_url=os.environ.get('OPENWEBUI_URL', 'http://localhost:3000') + '/api',
    api_key=os.environ['OPENWEBUI_API_KEY'],
)

resp = client.chat.completions.create(
    model='qwen3.5:9b',
    messages=[{'role': 'user', 'content': 'Résume en une phrase : texte fictif de test.'}],
)
print(resp.choices[0].message.content)
→
The /ollama/ proxy for native calls
The documentation also describes a proxy to Ollama under /ollama/ (for example /ollama/api/tags or /ollama/api/generate), protected by the same key. It lets you use the native Ollama format without exposing port 11434 to the network. Open WebUI assistants and knowledge bases don't apply there: it's the Ollama API, simply placed behind authentication.

#Open WebUI API authentication errors

Open WebUI is built on FastAPI: errors generally come back with an HTTP status code and a JSON body containing a detail field. The exact text varies by version; rely on the status code first, then read detail, but never log it together with the request headers.

401 Unauthorized
The key is missing, malformed, or revoked. Check for the exact Authorization: Bearer header followed by the key (a single space, no stray quotes), that the environment variable is actually loaded in the process running the script, and that the key hasn't been regenerated since.
401 with a key that used to work
API keys have been disabled by the administrator, or the key has been deleted. A session token (JWT) copied from the browser can also expire: use a real API key for scripts.
403 Forbidden
The key is recognized but the account lacks permission: API key permission removed, endpoint not on the allowed list if restrictions are enabled, account pending approval, or an admin endpoint called with a regular account.
Model not found
The id you sent doesn't match any model the account can access. Rerun lister_modeles.py and copy the exact id, including the tag (qwen3.5:9b, not qwen3.5).
HTML response instead of JSON
The URL points to the web page instead of the API: incomplete path (missing /api), a reverse proxy rewriting paths, or another application's address. Print resp.headers.get('content-type') to confirm.
Timeout or 5xx
The model is loading, there isn't enough VRAM, or Ollama is stopped. Test curl http://localhost:11434/api/tags on the Ollama host, then check the Open WebUI container logs.
Terminal — diagnostics without printing the key
# Code HTTP seul : 200 attendu si clé et droits sont corrects
curl -s -o /dev/null -w "%{http_code}\n" \
  -H "Authorization: Bearer $OPENWEBUI_API_KEY" \
  "$OPENWEBUI_URL/api/models"

# Comparer avec un appel sans clé : 401 attendu
curl -s -o /dev/null -w "%{http_code}\n" "$OPENWEBUI_URL/api/models"
!
Don't expose Ollama to work around an error
When you hit a 401 or 403, it's tempting to call port 11434 directly from another machine by setting OLLAMA_HOST=0.0.0.0. Ollama has no built-in authentication: the port becomes usable by the entire network. Fix the key or permissions instead, or go through the Open WebUI /ollama/ proxy.

#Limitations and sources

The Open WebUI API adds a layer of authentication and permissions, not a privacy guarantee in itself. If a model is served through a connection to an external provider, messages and document excerpts are sent to that provider, even through the local API. Over plain HTTP on a network, the key travels in cleartext: put the instance behind HTTPS as soon as it's reachable beyond localhost. Finally, the paths and options mentioned may change between versions; the official reference page is authoritative.

Open WebUI documentation, API Endpoints
https://docs.openwebui.com/reference/api-endpoints/ (consultée le 30/10/2026): authentification Bearer, /api/models, /api/chat/completions, relais /ollama/, fichiers et bases de connaissances.
Related QuelLLM guide
https://quelllm.fr/guide/ollama-api-rest-integration-python: appeler directement l'API REST d'Ollama en Python, sans Open WebUI.
Status of this procedure
Written from the documentation, not re-run for this guide. No model response, screenshot, or measurement is presented as observed; the examples use dummy data.
Search query
The search volume for the query “open webui api” could not be retrieved (DataForSEO, 30/10/2026, 402 response): no traffic data is claimed.

#Go further

Direct Ollama API
Ollama REST API: Python integration (/guide/ollama-api-rest-integration-python), for local scripts that need neither accounts nor documents.
Setting up the knowledge base
Open WebUI with Ollama: complete guide (/guide/open-webui-ollama-tutoriel), covering installation, connecting to Ollama, and user management.
Call an assistant
Open WebUI: create a reusable custom assistant (/guide/open-webui-creer-assistant-modele-personnalise), whose ID you then use as the model field in the API.
Isolate access
Open WebUI: manage document access (/guide/open-webui-groupes-acces-documents), to check what the script's account can actually query.
Did this guide help you?

Feedback, an error, or a clarification? Let us know—it improves the guide for everyone.