Roar AI
Get started
Resources

Claude Code API key: how to set it up and use it

How to use an API key with Claude Code on macOS, Linux and Windows, set ANTHROPIC_BASE_URL, choose a model, cap spending per key and fix common errors.

Claude Code can run on two kinds of account. You can sign in with a Claude subscription, or you can give it an API key and pay for exactly what it uses, token by token.

An API key suits people who use Claude Code in bursts, teams who want one bill and a spending limit for each person, and anyone running Claude Code in scripts or CI where nobody is there to sign in.

This guide explains how Claude Code decides which account to use, how to set an API key on macOS, Linux and Windows, how to point Claude Code at another API address with ANTHROPIC_BASE_URL, and how to fix the errors people run into most often.

Signing in with a plan or using an API key

When you start Claude Code for the first time, it asks you to sign in. Signing in with a Claude subscription means your usage counts against that plan's limits, and you pay the plan's fixed price whether you use it heavily or not at all.

An API key works differently. Claude Code sends every request with the key, and you are billed for the tokens each request reads and writes. There is no usage window to wait out, and no charge in a month you do not use it.

Subscription sign-inAPI key
How you payA fixed plan pricePer token, for what you use
LimitsThe plan's usage limitsYour own spending limits and the API's rate limits
Set up with/login in Claude CodeAn environment variable or the settings file
Works without a browserNo, it needs a sign-in onceYes, suits servers, scripts and CI
Shared across a teamOne plan per personKeys per person or per project, on one bill

Neither is better in every case. If you use Claude Code all day, every day, a plan can work out cheaper. If your use is uneven, or you need to control what each person spends, an API key is usually the better fit.

How Claude Code chooses which credential to use

Claude Code can find credentials in several places at once, and it uses the first one it finds in this order:

  1. Cloud provider settings such as CLAUDE_CODE_USE_BEDROCK or CLAUDE_CODE_USE_VERTEX
  2. ANTHROPIC_AUTH_TOKEN
  3. ANTHROPIC_API_KEY
  4. An apiKeyHelper script in your settings
  5. CLAUDE_CODE_OAUTH_TOKEN
  6. Your subscription sign-in from /login

This order explains most authentication surprises. A key set in your shell is used ahead of your subscription, even if you are signed in. And if both ANTHROPIC_AUTH_TOKEN and ANTHROPIC_API_KEY are set, the first one wins.

The two key variables send the key in different ways:

VariableHow the key is sent
ANTHROPIC_API_KEYIn the x-api-key header
ANTHROPIC_AUTH_TOKENIn the Authorization header, as Bearer <key>

The first time Claude Code sees ANTHROPIC_API_KEY in an interactive session, it asks whether to use it and remembers your answer. You can change that answer later under Use custom API key in /config. In non-interactive mode (claude -p), the key is always used when it is set.

Run /status inside Claude Code at any time to see which credential it is using.

How to set up a Claude Code API key

If you have not installed Claude Code yet, the native installer is the simplest route:

macOS, Linux or WSL

curl -fsSL https://claude.ai/install.sh | bash

Windows PowerShell

irm https://claude.ai/install.ps1 | iex

There are then two places to put the key: an environment variable in your shell, or Claude Code's own settings file.

Option 1: An environment variable

An environment variable applies to every Claude Code session started from that shell.

macOS (zsh)

echo 'export ANTHROPIC_API_KEY="your-key"' >> ~/.zshrc
source ~/.zshrc

Linux (bash)

echo 'export ANTHROPIC_API_KEY="your-key"' >> ~/.bashrc
source ~/.bashrc

Windows PowerShell

[Environment]::SetEnvironmentVariable("ANTHROPIC_API_KEY", "your-key", "User")

On Windows, close and reopen the terminal afterwards, because a window that was already open keeps its old environment. To set the variable for the current window only, use $env:ANTHROPIC_API_KEY = "your-key".

Option 2: Claude Code's settings file

Claude Code reads an env block from its settings file and applies it to every session, whichever terminal you start it from. The user settings file is:

SystemPath
macOS and Linux~/.claude/settings.json
Windows%USERPROFILE%\.claude\settings.json

~/.claude/settings.json

{
  "env": {
    "ANTHROPIC_API_KEY": "your-key"
  }
}

Values in this file are used exactly as written, so ~ and $HOME are not expanded. If the file already exists, add the env block alongside the settings already in it rather than replacing the file.

A project can also have its own .claude/settings.json, which is usually committed to the repository, and .claude/settings.local.json, which is not. Keep keys out of the committed file. If a key belongs to one project, put it in .claude/settings.local.json and check that file is in .gitignore.

Check that it worked

Start Claude Code with claude, approve the key if it asks, then run /status. It should show that an API key is in use. Send a short message to confirm the key is accepted.

What is the Anthropic base URL?

By default, Claude Code sends requests to Anthropic's own API. ANTHROPIC_BASE_URL changes that address, so Claude Code sends the same requests somewhere else: a company gateway, a proxy, or another provider that serves Claude models on Anthropic's Messages API.

The address you set is the root of the API, without /v1. Claude Code adds the paths itself, mainly /v1/messages for conversations and /v1/messages/count_tokens for counting tokens. If you include /v1 in the base URL, requests go to /v1/v1/messages and fail with a 404.

Setting ANTHROPIC_BASE_URL on its own does not change how you pay. If you are signed in with a subscription and no key variable is set, Claude Code still uses your sign-in. Set the key in the same place as the base URL.

A few Claude Code features behave differently with a custom base URL. Remote Control is turned off when the base URL points anywhere other than Anthropic's API, and Claude Code does not discover the available models automatically, so you choose them yourself (see below).

How to use Claude Code with Roar AI

Roar AI serves Claude models on Anthropic's Messages API, so Claude Code works with a Roar AI key without any other changes. Your usage appears in the same console, on the same bill, as everything else your team does through Roar AI.

  1. Create a free Roar AI account, then open API keys › New key in the console. Copy the key when it is shown, because it is displayed only once. Roar AI keys start with roar_live_.
  2. Set the base URL and the key, either in your shell or in ~/.claude/settings.json.

macOS or Linux

export ANTHROPIC_BASE_URL="https://api.roar-ai.com"
export ANTHROPIC_AUTH_TOKEN="roar_live_..."

Windows PowerShell

[Environment]::SetEnvironmentVariable("ANTHROPIC_BASE_URL", "https://api.roar-ai.com", "User")
[Environment]::SetEnvironmentVariable("ANTHROPIC_AUTH_TOKEN", "roar_live_...", "User")

~/.claude/settings.json

{
  "env": {
    "ANTHROPIC_BASE_URL": "https://api.roar-ai.com",
    "ANTHROPIC_AUTH_TOKEN": "roar_live_..."
  }
}

Roar AI accepts the key as either ANTHROPIC_AUTH_TOKEN or ANTHROPIC_API_KEY. Use one of them, not both. If you already have an Anthropic key in ANTHROPIC_API_KEY, remove it or ANTHROPIC_AUTH_TOKEN will take precedence and the two will be hard to tell apart.

  1. Start Claude Code and run /status to confirm it is using your key and the Roar AI address.

Requests reach Claude as Claude Code sends them, including tools, extended thinking, anthropic-beta headers and prompt caching. Streaming works as normal.

Claude Code with other models

Through Roar AI, Claude Code works with Claude models only. Anthropic's Messages API is served for Claude, and asking for any other model on it returns a 404 that names the closest Claude model available. Other models on Roar AI, such as GPT, Gemini, Llama and Qwen, are available on the OpenAI-compatible API at https://api.roar-ai.com/v1, which tools such as Cursor and the OpenAI SDKs use.

Choosing a model in Claude Code

Claude Code refers to models by alias: opus, sonnet, haiku and fable. You can switch during a session with /model, start a session with a particular model using claude --model sonnet, or set a default with the ANTHROPIC_MODEL variable.

You can also decide which exact model each alias uses. This is useful when you want every session, including the background tasks Claude Code runs on a smaller model, to use the versions you have chosen:

~/.claude/settings.json

{
  "env": {
    "ANTHROPIC_BASE_URL": "https://api.roar-ai.com",
    "ANTHROPIC_AUTH_TOKEN": "roar_live_...",
    "ANTHROPIC_DEFAULT_OPUS_MODEL": "claude-opus-5-5",
    "ANTHROPIC_DEFAULT_SONNET_MODEL": "claude-sonnet-5-5",
    "ANTHROPIC_DEFAULT_HAIKU_MODEL": "claude-haiku-5-5"
  }
}
VariableWhat it sets
ANTHROPIC_MODELThe model Claude Code starts with
ANTHROPIC_DEFAULT_OPUS_MODELThe model the opus alias uses
ANTHROPIC_DEFAULT_SONNET_MODELThe model the sonnet alias uses
ANTHROPIC_DEFAULT_HAIKU_MODELThe model the haiku alias uses, including for background tasks
CLAUDE_CODE_SUBAGENT_MODELThe default model for subagents

Roar AI accepts model names with or without Anthropic's date suffix, so a dated name such as claude-haiku-4-5-20251001 reaches the same model as claude-haiku-4-5. The Claude API page lists the Claude models available on Roar AI.

As a starting point, Sonnet handles most everyday coding well, Opus is worth it for large refactors and difficult debugging, and Haiku is the economical choice for quick edits and background work.

How billing works with an API key

With an API key, every request is billed by the tokens it uses:

  • Input tokens are everything Claude Code sends: your message, the files it has read, the conversation so far and its own instructions.
  • Output tokens are what Claude writes back, including code and reasoning.
  • Cached input tokens are parts of the input that were sent recently and are reused, such as a long system prompt. They are billed at a lower rate than ordinary input.

Claude Code sessions are input-heavy. As a session grows, each request carries more of the conversation and more of the files Claude has read, so long sessions cost more per message than short ones. Prompt caching does much of the work of keeping that down, and Claude Code uses it automatically. Starting a new session with /clear when you change task, and using /compact in long sessions, keeps the input smaller.

Roar AI publishes a rate for each Claude model and bills every call at that rate, with no fee added on top. Counting tokens with /v1/messages/count_tokens is free. The Claude API page shows the current rates, and every request appears in the console's usage view with its model, tokens and cost.

Setting a spending limit on each key

The main risk with an API key is spending you did not expect: a long agent run, a loop in a script, or a key that has leaked. A limit on each key keeps that contained.

In the Roar AI console, open a key to set:

  • A spend cap for a day, a week, a month or the key's whole life. When a hard cap is reached, further requests are refused until the period resets. You can instead choose to receive an email warning and let requests continue.
  • A rate limit in requests per minute.
  • An expiry date, after which the key stops working.

Caps can also be set on a project, which groups several keys, and on the whole workspace. The tightest limit that applies is the one that counts. A common setup is one key per person, each with its own monthly cap, inside a project with a team budget.

If a key leaks, revoke it in the console. Revocation takes effect immediately.

Common errors and how to fix them

What you seeLikely causeHow to fix it
401 authentication errorThe key is missing, mistyped, revoked or expiredCheck the value with /status, then create a new key if needed
Requests still use your subscriptionNo key variable is set where Claude Code can see it, or you declined the key promptSet the key next to the base URL, restart the terminal, and check Use custom API key in /config
A different key is used than the one you setANTHROPIC_AUTH_TOKEN and ANTHROPIC_API_KEY are both setRemove the one you do not want
404 on every requestThe base URL ends in /v1Set ANTHROPIC_BASE_URL to https://api.roar-ai.com
404 naming a modelThe model is not served on the Messages API, or the name is wrongUse a Claude model; the error suggests the closest one
402The key, project or workspace has reached its spend cap, or the account has run out of creditRaise the cap or add credit in the console
429Too many requests per minuteWait for the time in the retry-after header, or raise the key's rate limit
A variable set in the settings file is ignored~ or $HOME in the value, or the JSON is invalidWrite the full value, and validate the file
A new variable is not picked up on WindowsThe terminal was opened before the variable was setClose and reopen the terminal

Every response from Roar AI carries a request ID in the x-request-id header. If you contact support, include it, and the request can be found in your usage view.

Frequently asked questions

Do I need an API key to use Claude Code?

No. Claude Code works with a Claude subscription sign-in, an API key, or a cloud provider account. An API key is needed when you want to pay per token, run Claude Code without signing in through a browser, or send its requests through a gateway such as Roar AI.

Where does Claude Code store its API key?

Claude Code reads the key from the environment variable ANTHROPIC_API_KEY or ANTHROPIC_AUTH_TOKEN, or from the env block in its settings file at ~/.claude/settings.json (on Windows, %USERPROFILE%\.claude\settings.json). A key can also come from an apiKeyHelper script, which is useful when keys are kept in a password manager or secrets service.

What is the difference between ANTHROPIC_API_KEY and ANTHROPIC_AUTH_TOKEN?

ANTHROPIC_API_KEY sends the key in the x-api-key header, and Claude Code asks you to approve it once in interactive sessions. ANTHROPIC_AUTH_TOKEN sends it in the Authorization: Bearer header and takes precedence if both are set. Roar AI accepts either.

What should ANTHROPIC_BASE_URL be set to?

It should be the root address of the API, without /v1. For Roar AI, set ANTHROPIC_BASE_URL to https://api.roar-ai.com. Claude Code adds /v1/messages itself.

Can I use Claude Code with a key and keep my subscription?

Yes, but not at the same time. When a key variable is set, Claude Code uses it ahead of your sign-in. To go back to your subscription, remove the variable (unset ANTHROPIC_API_KEY on macOS or Linux) or turn off Use custom API key in /config.

Can Claude Code use models other than Claude through Roar AI?

No. Through Roar AI, Claude Code works with Claude models only. Roar AI's other models, including GPT, Gemini and open-source models, are available on its OpenAI-compatible API for tools that use that format.

How do I stop Claude Code from spending too much?

Give each person or project its own key, and set a spend cap on it in the Roar AI console. A hard cap refuses further requests once it is reached, so a long session or a runaway script cannot spend beyond it.

Is it cheaper to use Claude Code with an API key?

It depends on how much you use it. With an API key you pay only for the tokens you use, so light or uneven use usually costs less than a subscription. Heavy daily use can cost more. Your usage view shows what each session actually cost, which is the most reliable way to compare.

Getting started

To try Claude Code on a Roar AI key, create a free account, make a key with a spend cap, and set ANTHROPIC_BASE_URL and ANTHROPIC_AUTH_TOKEN as shown above. The quickstart covers the same key with the Anthropic and OpenAI SDKs.

Start building
in minutes

Get a key, call any model, ship your app. Pay in your local currency.