Table of Contents
What OpenRouter is
OpenRouter is a prepaid gateway in front of hundreds of AI models from Anthropic, OpenAI, Google, DeepSeek, MiniMax and others. You call one API with one key, and OpenRouter forwards each request to a provider that hosts the model you named.
- Your program or tool sends a request to
https://openrouter.ai/api/v1/...with a model slug such asdeepseek/deepseek-v4-flash. - OpenRouter picks a provider serving that model, and tries another if the first is down or rate limited.
- The answer comes back in the same response format whichever provider served it, with token counts and cost.
- The cost is taken from your prepaid credit and recorded on your Activity page.
The same key covers several kinds of request:
| Endpoint | What it does |
|---|---|
/api/v1/chat/completions | Chat and vision, OpenAI-compatible format |
/api/v1/embeddings | Text to vectors, for search and RAG |
/api/v1/images | Image generation |
/api/v1/audio/speech, /api/v1/audio/transcriptions | Text to speech, speech to text |
/api/v1/messages (Anthropic format) | What Claude Code talks to |
/api/v1/models | The model catalog with prices; no key needed |
Why use OpenRouter
In short: one key for every model, you pay only for what you use, and you switch models by changing one string.
- One key, many models. Switching models means changing a slug such as
minimax/minimax-m3ordeepseek/deepseek-v4-flash. No new account or SDK. - Standard request shapes. The chat endpoint follows the OpenAI format, so any OpenAI-compatible client works with a different base URL. An Anthropic-compatible endpoint lets Claude Code run against any model.
- Pay as you go, with a cap. Buy credit once and set a spending limit and expiry date per key. Hitting the cap returns a 402 error, not a bill.
- Free models. Slugs ending in
:freecost nothing, with request limits. - An audit trail. The Activity page lists every request with its model, tokens and cost. That is the proof of which model actually ran, since a model’s answer to “who are you?” is not.
- More than chat. The same key covers embeddings, vision, image generation and audio.
The trade-off: you add a middleman between you and the provider, and OpenRouter’s fees apply to credit purchases.
Setup
You need an account, some credit and one key with a spending cap. Everything else reads that key from the OPENROUTER_API_KEY environment variable.
- Sign in at openrouter.ai and buy credit. $10–20 is enough to start; fees may apply at checkout.
- At Settings > Keys, create a key with a recognizable name, a credit limit (start at $5–10) and an expiry date.
- Enter the key into a hidden prompt for the current terminal only. Never put it in a source file, a prompt, a screenshot or a Git commit.
macOS / Linux (zsh):
read -s "OPENROUTER_API_KEY?Paste your OpenRouter key (hidden): "
export OPENROUTER_API_KEY
Windows PowerShell:
$k = Read-Host "Paste your OpenRouter key" -AsSecureString
$env:OPENROUTER_API_KEY = [System.Net.NetworkCredential]::new('', $k).Password
Remove-Variable k
If you want the key kept between terminals, store it as a user environment variable (setx OPENROUTER_API_KEY ... on Windows, or an export line in ~/.zshrc). It’s more convenient, but any program you run can then read it.
Picking a model
A model is named by a slug, vendor/model. Prices are per million tokens, from the models API on October 29, 2026.
| Slug | Input $/M | Output $/M | Use |
|---|---|---|---|
minimax/minimax-m3 | 0.30 | 1.20 | Solid default for Claude Code and chat |
xiaomi/mimo-v2.6-flash | 0.14 | 0.28 | Cheaper; good for app calls |
deepseek/deepseek-v4-flash | 0.09 | 0.18 | Cheap, 1M context |
poolside/laguna-s-2.1:free | 0 | 0 | Free; coding-agent model, rate limited |
Claude Code needs a model that supports tool calls; the model page lists “tools” under supported parameters.
1. Quick test with curl
One chat request proves the key, the credit and the model all work. Expect a short answer and a usage object with token counts and cost.
macOS / Linux:
curl -s https://openrouter.ai/api/v1/chat/completions \
-H "Authorization: Bearer $OPENROUTER_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "minimax/minimax-m3",
"max_tokens": 500,
"messages": [{"role": "user", "content": "Reply with the single word OK."}]
}'
Windows PowerShell (JSON quoting through curl.exe is fragile in PowerShell 5.1, so this uses the built-in client):
$body = @{
model = "minimax/minimax-m3"
max_tokens = 500
messages = @(@{ role = "user"; content = "Reply with the single word OK." })
} | ConvertTo-Json -Depth 5
$r = Invoke-RestMethod https://openrouter.ai/api/v1/chat/completions -Method Post `
-Headers @{ Authorization = "Bearer $env:OPENROUTER_API_KEY" } `
-ContentType "application/json" -Body $body
$r.choices[0].message.content; $r.usage
Two more checks that cost nothing:
# Your key's limit and usage so far
curl -s https://openrouter.ai/api/v1/key -H "Authorization: Bearer $OPENROUTER_API_KEY"
# Every model, with prices and supported parameters (no key needed)
curl -s https://openrouter.ai/api/v1/models
An empty reply with finish_reason: "length" means a reasoning model spent its output budget thinking. Raise max_tokens, or add "reasoning": {"enabled": false} for models where that doesn’t hurt quality. Test that per model: on some it lowers accuracy.
2. Claude Code through OpenRouter
Claude Code talks to whatever server ANTHROPIC_BASE_URL names. OpenRouter serves an Anthropic-compatible endpoint at https://openrouter.ai/api, so a few environment variables point Claude Code at any OpenRouter model. No Claude subscription is needed.
| Variable | Value | Why |
|---|---|---|
ANTHROPIC_BASE_URL | https://openrouter.ai/api | Send requests to OpenRouter |
ANTHROPIC_AUTH_TOKEN | your OpenRouter key | Authenticate |
ANTHROPIC_API_KEY | empty | Stop a real Anthropic key from taking over |
ANTHROPIC_DEFAULT_FABLE_MODEL, ..._OPUS_MODEL, ..._SONNET_MODEL, ..._HAIKU_MODEL | your slug | Every /model choice routes to your model, not a pricier Anthropic one |
CLAUDE_CODE_SUBAGENT_MODEL | your slug | Subagents use it too |
Set the variables in a terminal, then run claude in that same terminal. They last only until the window closes, and the key is never written to disk.
Windows PowerShell
$k = Read-Host "OpenRouter key" -AsSecureString
$env:OPENROUTER_API_KEY = [System.Net.NetworkCredential]::new('', $k).Password
Remove-Variable k
$m = "minimax/minimax-m3"
$env:ANTHROPIC_BASE_URL = "https://openrouter.ai/api"
$env:ANTHROPIC_AUTH_TOKEN = $env:OPENROUTER_API_KEY
$env:ANTHROPIC_API_KEY = ""
$env:ANTHROPIC_DEFAULT_FABLE_MODEL = $m
$env:ANTHROPIC_DEFAULT_OPUS_MODEL = $m
$env:ANTHROPIC_DEFAULT_SONNET_MODEL = $m
$env:ANTHROPIC_DEFAULT_HAIKU_MODEL = $m
$env:CLAUDE_CODE_SUBAGENT_MODEL = $m
claude --model $m
macOS / Linux (zsh)
read -s "OPENROUTER_API_KEY?OpenRouter key (hidden): "; echo
m="minimax/minimax-m3"
export ANTHROPIC_BASE_URL="https://openrouter.ai/api"
export ANTHROPIC_AUTH_TOKEN="$OPENROUTER_API_KEY"
export ANTHROPIC_API_KEY=""
export ANTHROPIC_DEFAULT_FABLE_MODEL="$m"
export ANTHROPIC_DEFAULT_OPUS_MODEL="$m"
export ANTHROPIC_DEFAULT_SONNET_MODEL="$m"
export ANTHROPIC_DEFAULT_HAIKU_MODEL="$m"
export CLAUDE_CODE_SUBAGENT_MODEL="$m"
claude --model "$m"
In bash, use read -rsp "OpenRouter key (hidden): " OPENROUTER_API_KEY for the first line.
Until you close it, every claude you start in that terminal goes through OpenRouter, and --continue resumes the last session. To use your normal Claude account, open a new terminal.
Verify it
- Run
/status: the model is your slug and the API destination is OpenRouter. - Ask the agent to read a file and report something you can check, such as a line count.
- Open OpenRouter Activity and confirm the request was billed to your slug.
To change models, exit, set the variables again with a new slug, and relaunch: /model inside the session still routes to the launch slug. For a 1M-token context on a model that supports it, add [1m] to the slug.
3. Python
There are three ways in, from fewest dependencies to most convenient. All read the key from OPENROUTER_API_KEY.
Standard library only
No dependencies, and you see the raw request.
import json, os, urllib.request
body = {
"model": "minimax/minimax-m3",
"max_tokens": 500,
"messages": [
{"role": "system", "content": "You are concise."},
{"role": "user", "content": "Name three uses of embeddings."},
],
}
req = urllib.request.Request(
"https://openrouter.ai/api/v1/chat/completions",
data=json.dumps(body).encode(),
headers={"Authorization": f"Bearer {os.environ['OPENROUTER_API_KEY']}",
"Content-Type": "application/json"},
)
d = json.load(urllib.request.urlopen(req))
print(d["choices"][0]["message"]["content"])
print(d["usage"])
The OpenAI SDK with a different base URL
Any OpenAI-compatible client works. pip install openai:
import os
from openai import OpenAI
client = OpenAI(base_url="https://openrouter.ai/api/v1",
api_key=os.environ["OPENROUTER_API_KEY"])
r = client.chat.completions.create(
model="deepseek/deepseek-v4-flash",
messages=[{"role": "user", "content": "Name three uses of embeddings."}],
)
print(r.choices[0].message.content, r.usage)
The same client also reaches a local Ollama model: set base_url="http://localhost:11434/v1".
The official openrouter SDK
One client also covers embeddings, images and audio. pip install openrouter:
import os
from openrouter import OpenRouter
client = OpenRouter(api_key=os.environ["OPENROUTER_API_KEY"])
c = client.chat.send(
model="minimax/minimax-m3",
max_tokens=500,
messages=[{"role": "user", "content": "Name three uses of embeddings."}],
)
print(c.choices[0].message.content)
print(c.usage.prompt_tokens, c.usage.completion_tokens, getattr(c.usage, "cost", None))
The same client exposes client.embeddings.generate(...) and client.images.generate(...). One catch: the SDK turns reasoning off with reasoning={"effort": "none"}, not the raw API’s {"enabled": False}, which it silently drops.
4. Spring AI
Spring AI has no OpenRouter module. Use its OpenAI starter and point the base URL at OpenRouter. In Spring AI 2.x the base URL must end in /v1.
Why /v1: since 2.0, the OpenAI module wraps the official openai-java SDK and passes base-url through unchanged (OpenAiSetup.calculateBaseUrl, v2.0.2). Its own default is https://api.openai.com/v1. Spring AI 1.x tutorials use https://openrouter.ai/api without /v1; that is the 1.x form.
Dependencies (Maven)
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-bom</artifactId>
<version>2.0.2</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-starter-model-openai</artifactId>
</dependency>
</dependencies>
Gradle: implementation platform("org.springframework.ai:spring-ai-bom:2.0.2") and implementation "org.springframework.ai:spring-ai-starter-model-openai".
application.yml
spring:
ai:
openai:
base-url: https://openrouter.ai/api/v1
api-key: ${OPENROUTER_API_KEY}
chat:
model: minimax/minimax-m3
temperature: 0.7
The key still comes from the environment; it never goes in the file.
A controller with ChatClient
@RestController
class ChatController {
private final ChatClient chat;
ChatController(ChatClient.Builder builder) {
this.chat = builder
.defaultSystem("You are concise.")
.build();
}
@GetMapping("/ask")
String ask(@RequestParam String q) {
return chat.prompt().user(q).call().content();
}
}
Run it with ./mvnw spring-boot:run and open http://localhost:8080/ask?q=Name+three+uses+of+embeddings. To pick a different model for one call, pass options: chat.prompt().user(q).options(OpenAiChatOptions.builder().model("deepseek/deepseek-v4-flash").build()).
OpenRouter-only request fields, such as reasoning, go under spring.ai.openai.chat.extra-body (Spring AI OpenAI chat docs).
Troubleshooting
| Symptom | Likely cause and fix |
|---|---|
| 401 Unauthorized | Key not set in this terminal, or revoked. Re-enter it; never print it to check |
| 402 Payment Required | Credit used up or the key’s cap reached. Check /api/v1/key and the account balance |
| 404 or “model not found” | Wrong slug, or wrong base URL path (/api vs /api/v1). Compare with the models list |
404 “no endpoints found” on a :free model | Privacy settings block providers that log prompts. Adjust them in OpenRouter settings, or use a paid model |
| 429 Too Many Requests | Rate limit, common on free models. Wait, or switch model |
Empty reply, finish_reason: length | Reasoning used the whole budget. Raise max_tokens or turn reasoning off per model |
| Claude Code asks for a Claude plan | The variables aren’t set in this terminal. Set them, then run claude in the same window |
| Claude Code “model isn’t described by this version’s model catalog” | Only a warning; context is capped at 200K. Add [1m] for models with a 1M window |
Sources
- Claude Code: Up and Running examples: the same variables wrapped in launcher scripts
- OpenRouter quick start and docs
- OpenRouter with Claude Code
- OpenRouter limits
- OpenRouter models API, prices read October 29, 2026
- Spring AI OpenAI chat reference (2.0.2)
- Spring AI
OpenAiSetup.java, v2.0.2
About the Author
Wei Li is a passionate software professional who builds enterprise applications with modern technologies. The guides here come from that work: each one explains a feature and shows it in working code. Read more on the About page, or find Wei Li on GitHub. |