Skip to content
Wei Li
Go back

Introduction to OpenRouter

Edit page
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.

  1. Your program or tool sends a request to https://openrouter.ai/api/v1/... with a model slug such as deepseek/deepseek-v4-flash.
  2. OpenRouter picks a provider serving that model, and tries another if the first is down or rate limited.
  3. The answer comes back in the same response format whichever provider served it, with token counts and cost.
  4. The cost is taken from your prepaid credit and recorded on your Activity page.
A request goes from your app to OpenRouter, which tries a first provider, falls back to a second one when the first fails, returns the answer with usage and cost, and charges your credit

The same key covers several kinds of request:

EndpointWhat it does
/api/v1/chat/completionsChat and vision, OpenAI-compatible format
/api/v1/embeddingsText to vectors, for search and RAG
/api/v1/imagesImage generation
/api/v1/audio/speech, /api/v1/audio/transcriptionsText to speech, speech to text
/api/v1/messages (Anthropic format)What Claude Code talks to
/api/v1/modelsThe 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.

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.

  1. Sign in at openrouter.ai and buy credit. $10–20 is enough to start; fees may apply at checkout.
  2. At Settings > Keys, create a key with a recognizable name, a credit limit (start at $5–10) and an expiry date.
  3. 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.

SlugInput $/MOutput $/MUse
minimax/minimax-m30.301.20Solid default for Claude Code and chat
xiaomi/mimo-v2.6-flash0.140.28Cheaper; good for app calls
deepseek/deepseek-v4-flash0.090.18Cheap, 1M context
poolside/laguna-s-2.1:free00Free; 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.

VariableValueWhy
ANTHROPIC_BASE_URLhttps://openrouter.ai/apiSend requests to OpenRouter
ANTHROPIC_AUTH_TOKENyour OpenRouter keyAuthenticate
ANTHROPIC_API_KEYemptyStop a real Anthropic key from taking over
ANTHROPIC_DEFAULT_FABLE_MODEL, ..._OPUS_MODEL, ..._SONNET_MODEL, ..._HAIKU_MODELyour slugEvery /model choice routes to your model, not a pricier Anthropic one
CLAUDE_CODE_SUBAGENT_MODELyour slugSubagents 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

  1. Run /status: the model is your slug and the API destination is OpenRouter.
  2. Ask the agent to read a file and report something you can check, such as a line count.
  3. 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

SymptomLikely cause and fix
401 UnauthorizedKey not set in this terminal, or revoked. Re-enter it; never print it to check
402 Payment RequiredCredit 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 modelPrivacy settings block providers that log prompts. Adjust them in OpenRouter settings, or use a paid model
429 Too Many RequestsRate limit, common on free models. Wait, or switch model
Empty reply, finish_reason: lengthReasoning used the whole budget. Raise max_tokens or turn reasoning off per model
Claude Code asks for a Claude planThe 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

About the Author

Wei Li

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.


Edit page
Share this post:

Previous Post
Moving a GitHub Pages Site to Your Own Domain
Next Post
20 Unix Commands Worth Knowing Well