Claude Code API key: setup, billing, spend caps and errors
Run Claude Code on a Console API key: create it, set ANTHROPIC_API_KEY or apiKeyHelper, a key beside a plan login, per-token prices, spend caps, errors.
To run Claude Code on an Anthropic API key, buy prepaid credits on the Claude Console’s Billing page, create a key on its API keys page (platform.claude.com/settings/keys), and set it as ANTHROPIC_API_KEY before you start claude. An interactive session asks once whether to use the key; claude -p uses it without asking. Or choose the Anthropic Console account at /login and Claude Code signs in to the Console for you. Requests are then billed per token from that credit balance instead of drawing on a plan’s five-hour and weekly allowance: on the default model, Opus 5.5, $4 per million input tokens and $20 per million output, as of November 23, 2026. If you also pay for a Claude plan, an approved key in the environment wins over the plan’s login, and /status shows which one a session is using.
Getting a key
Keys come from the Claude Console, Anthropic’s API account, which is separate from a claude.ai subscription and usually paid for in advance. Per Anthropic’s article on paying for API usage, someone with the Admin or Billing role opens platform.claude.com/settings/billing and clicks Buy credits. The credits are usable at once, cover “API access, playground usage, and Claude Code,” expire one year after purchase and are non-refundable. Then, on the API keys page, click Create key:
- Expiration. 3 hours, 1 day, 7 days, 30 days, a custom length, or Never. It can’t be changed later. Anthropic emails a warning 7 days ahead only for keys made to last at least 14 days, and 1 day ahead for keys of at least 7 days; an expired key gets
401 authentication_errorand can only be deleted. - Linked account. Yourself, for a personal key, which acts as you and stops working if you lose access to the organization. For a server or a CI job, the API authentication docs say to have an admin create a service account and link the key to that instead.
- Workspace. Scope the key to one. Those docs say a key that isn’t scoped to a workspace must name one in an
anthropic-workspace-idheader on every request, and a workspace is also what you can put a spend limit on later.
The key starts sk-ant-api. On a team Console organization, an admin invites you from the Members page with the Claude Code role, which can only create Claude Code keys, or Developer, which can create any.
You can also skip handling a key. Run /login and choose the Anthropic Console account (from the shell, claude auth login --console signs in to the Console for API billing). Since version 2.1.242 that screen offers two routes, unless an admin’s settings remove the keyless one, per the authentication docs: Sign in with your Console account, marked recommended, which keeps an OAuth login that Claude Code renews and creates no key; and Create an API key, marked legacy, which mints a key and saves it with your other credentials. Both bill the Console organization. The keyless route needs ANTHROPIC_API_KEY unset first, and it signs you out of any claude.ai login stored on the machine. A key made this way lives in a workspace the Console creates called “Claude Code”, where nobody can create keys by hand and which is the only workspace with per-user monthly spend limits. /logout removes a saved key.
Where Claude Code reads the key from
| Source | Set it | Behaviour |
|---|---|---|
ANTHROPIC_API_KEY | Exported in the shell that starts claude | Sent as the X-Api-Key header. Outranks apiKeyHelper and every plan login. |
apiKeyHelper | A command in settings.json that prints the key | Cached five minutes, run again after that or when a request fails with 401 or 403. |
Console login | /login, Anthropic Console account | Saved by Claude Code; removed by /logout. |
The variable, for one shell:
# macOS, Linux, WSL
export ANTHROPIC_API_KEY="your-key"
claude
# Windows PowerShell
$env:ANTHROPIC_API_KEY = "your-key"
claudeCopiedAnthropic’s help article on the variable makes it permanent with an export line in ~/.zshrc or ~/.bash_profile, or on Windows under System Properties, then Advanced, then Environment Variables. The same article lists forgetting such a line as a common mistake: a key set there reaches every session, including the ones you meant to run on a plan. The env block of a settings file can carry it as well, but the settings reference warns that values there are plain text in the file and reach every subprocess Claude Code starts, and points API credentials at apiKeyHelper. Keep it out of a project’s .claude/settings.json above all: Anthropic’s settings docs tell teams to commit that file.
A helper suits a key kept in a vault or rotated on a schedule, and works for a plain key in a file too. Claude Code runs the command through /bin/sh (cmd on Windows) and sends what it prints as the key, so it must print the key and nothing else: a banner or log line on stdout makes the helper fail. On macOS, Linux or WSL, store the key readable by you alone, without a trailing newline:
mkdir -p ~/.config/claude-code
# paste the key at the silent prompt
(umask 077; read -rs k; printf '%s' "$k" > ~/.config/claude-code/api-key)CopiedThen in ~/.claude/settings.json:
{
"apiKeyHelper": "cat ~/.config/claude-code/api-key"
}CopiedSwap cat for your vault’s command, as in Anthropic’s own example, vault kv get -field=api_key secret/llm-gateway/claude-code. For a credential that expires faster than five minutes, set CLAUDE_CODE_API_KEY_HELPER_TTL_MS to the refresh interval in milliseconds. A helper defined in a project’s settings doesn’t run in an interactive session until you accept the workspace trust prompt, and an exported ANTHROPIC_API_KEY still takes priority over it.
A key for a gateway or another provider, such as OpenRouter, goes in ANTHROPIC_AUTH_TOKEN with ANTHROPIC_BASE_URL, not here; the settings for that are in OpenRouter in Claude Code, Codex and OpenCode.
A key and a subscription on the same machine
When several credentials are present, Claude Code picks one in a fixed order: ANTHROPIC_AUTH_TOKEN, then ANTHROPIC_API_KEY, then apiKeyHelper, then a CLAUDE_CODE_OAUTH_TOKEN from claude setup-token, then Anthropic profiles, and last the plan login from /login, with Bedrock, Google Cloud and Foundry ahead of all of them when selected. Anthropic’s help article puts the consequence plainly: with a key set, “you’ll be charged via API pay-as-you-go rates using the API account associated with that key,” even if you’re logged in with a claude.ai subscription. How the key behaves at that point:
- Interactive sessions ask once whether to use a key found in the environment, and remember the answer. To change it, use the “Use custom API key” toggle in
/config, which only appears while the variable is set. claude -pnever asks: “the key is always used when present.”/statustells you which one is live. It shows anAPI keyrow, and with both configured it marks the credential that isn’t in use. Since 2.1.326,/loginalso says when requests still go out on an approved key, instead of ending on “Login successful”.- Cloud sessions ignore it. They always use the subscription, even with the variable set in the cloud environment.
- Update to 2.1.325 or later if you use background sessions: before it, a background session started on a claude.ai login could use and bill a key or token from the shell that started the background service.
That gives two ways to keep both on one machine on purpose. Leave the key exported and decline it at the prompt: interactive sessions then run on the plan and -p jobs bill the key. Or keep the key out of your profile and hand it only to the command that should bill the Console, and strip it from one that shouldn’t:
ANTHROPIC_API_KEY="$(cat ~/.config/claude-code/api-key)" claude -p "Triage the open issues"
env -u ANTHROPIC_API_KEY claudeCopiedIf you meant to use the plan and see a credit-balance error, a key is winning; the credit-balance-too-low guide shows how to find where it is set.
What doesn’t work on a key
Anthropic’s feature table lists what needs a claude.ai sign-in and is “not reachable with an Anthropic Console API key”: cloud sessions and Claude Code on mobile, Claude Code in Slack, Claude Code Desktop, cloud scheduled tasks (/schedule), Ultrareview, Code Review, Remote Control, the Chrome extension, computer use, Artifacts and voice dictation. The exception is Claude Desktop on 3P, the edition an organization sets up for other providers, which runs the Code tab with a Console key. The CLI takes a key, and so do the surfaces that wrap it: the VS Code extension, the Agent SDK and GitHub Actions. On a claude.ai Team or Enterprise organization, its server-managed settings don’t reach a session that runs on a key either.
What it costs
On the Anthropic API, Claude Code’s default model is Opus 5.5 (model configuration); no Fable model is a default anywhere, and /model fable selects Fable 5.2. List prices from the Claude API pricing page, per million tokens in US dollars, as of November 23, 2026:
| Model | Input | Cache write, 5 min | Cache write, 1 hour | Cache hit | Output |
|---|---|---|---|---|---|
Opus 5.5 | $4 | $5 | $8 | $0.20 | $20 |
Sonnet 5.5 | $2 | $2.50 | $4 | $0.10 | $10 |
Haiku 5.5 | $0.10 | $0.125 | $0.20 | $0.01 | $0.50 |
Fable 5.2 | $8 | $10 | $16 | $0.20 | $40 |
Haiku 5.5’s row is for prompts up to 100,000 tokens; a longer prompt pays $0.50 input and $2.50 output. Anthropic’s costs page gives its own average across enterprise deployments as “around $13 per developer per active day and $150-250 per developer per month, with costs remaining below $30 per active day for 90% of users.”
Caching is the lever specific to a key. A coding session re-sends the whole conversation every turn, and Claude Code caches it; on a plan, within its included usage, the main conversation gets a one-hour cache, but on an API key the default is five minutes. Step away for longer and the next turn writes the whole prefix again. At Opus 5.5 list price, re-caching a 200,000-token conversation costs $1.00 at the five-minute write rate, against $0.04 to read it from a warm cache (arithmetic, not a measurement). To give a key’s main conversation the hour, set "promptCacheTtl": "1h" in your settings (version 2.1.242 or later). The main conversation’s cache writes then cost the one-hour rate, $8 instead of $5 on Opus 5.5, which Anthropic says costs more on “short bursts of work that never idle past five minutes”, so it pays when breaks of five minutes to an hour are common.
Inside Claude Code, /usage shows a session cost that it computes locally at list price; the billed figures are in the Console (checking your Claude Code usage covers both screens). One point Anthropic’s help articles disagree on, as read November 23, 2026: the monthly API credits that come with Max, Ultra and Team plans. The monthly credits article says they don’t cover interactive Claude Code but do cover claude -p and the Agent SDK “when you run them yourself with an API key from your linked Claude Console organization,” and not runs started by the GitHub Action, an IDE extension or the desktop app. The billing article says flatly that they “can’t be used in Claude Code.”
Capping the spend
A prepaid balance is a cap of its own: when it runs out, requests stop. Auto-reload on the Billing page tops it up when it falls below an amount you set, which keeps long jobs running and removes that stop, so treat it as the opposite of a limit. The limits themselves work at three levels:
- The organization. An organization on the Start, Build or Scale tier has a monthly cap set by its usage tier: $500 on Start, $1,000 on Build, $200,000 on Scale. A new organization can start on an Evaluation tier with limits below these, and the Custom tier has no cap. On
platform.claude.com/settings/spend-limitsyou can set your own limit below it with Set limit or Adjust limit. At the tier cap, usage pauses until 00:00 UTC on the first of the next month, unless the organization moves up a tier first, which you ask for with Request tier increase on the Rate limits page. - A workspace. The same page sets a monthly limit per workspace, with email alerts at an amount you choose. The Claude Code workspace also takes a limit per user. Anthropic warns that a limit on the Default Workspace might not stop Claude Code usage from a member signed in with a Console account there; the organization limit still does.
- One run.
claude -p --max-budget-usd 5.00stops a print-mode run once its estimated spend reaches the amount. The CLI reference is careful about it: the estimate is client-side and “can differ from your bill,” subagents count toward it, and “spend can pass the cap,” so leave headroom.
On a server or in CI
Anthropic’s docs call an API key “a static credential”: nothing has to be refreshed in the background, which suits work nobody is watching, and it lasts until the expiry you set. Link the key to a service account, give it an expiry you will notice, and hand it only to the job. Then:
- Put the key in the job’s own environment. The error reference’s fix for
Not logged inis to confirm the key “is set and exported in the shell where you launchedclaude”, and a cron job or a systemd unit doesn’t read your~/.bashrc(why a job finds no credential). - Run it in bare mode.
--bareskips the machine’s hooks, plugins, MCP servers and CLAUDE.md, and Anthropic says it “will become the default for-pin a future release.” It never reads OAuth credentials, so it needs a key, from the variable or from a helper passed with--settings. - Strip the key from what Claude runs.
CLAUDE_CODE_SUBPROCESS_ENV_SCRUB=1removesANTHROPIC_API_KEYand other credentials from the environment of the Bash commands, hooks and stdio MCP servers Claude Code starts, which the env-vars reference says “reduces what a prompt injection attack can read.” The scrub covers environment variables only; it doesn’t hide a key file that a helper reads.
export CLAUDE_CODE_SUBPROCESS_ENV_SCRUB=1
# ANTHROPIC_API_KEY comes from the job's secret store
claude --bare -p "Summarise the failures in ci.log" \
--allowedTools "Read" --max-budget-usd 2.00CopiedTo see what a machine’s account finds, claude auth status prints JSON whose authMethod is one of none, claude.ai, oauth_token, api_key, api_key_helper or third_party, and exits 1 when there is no credential. In GitHub Actions, store the key as a repository secret and pass it to Anthropic’s action:
- uses: anthropics/claude-code-action@v1
with:
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}Copied/install-github-app inside Claude Code saves the secret under that name for you. The GitHub Actions docs add that deleting the secret leaves the key valid: delete it in the Console as well. A job that should spend a plan rather than the Console takes a one-year token from claude setup-token instead, with no key anywhere in its environment; the timer, permissions and alerting around either are in running Claude Code headless on a schedule.
The errors a key gives
All from Anthropic’s error reference. Whatever the message, /status first: it shows which credential the session is actually sending.
Not logged in · Please run /login
No credential reached this session. If you expected the key to cover it, check that ANTHROPIC_API_KEY is set and exported in the shell or unit that launched claude, not only in another one.
Invalid API key · Fix external API key
The API rejected the key from the variable or the helper, or Claude Code blocked it before sending. If the message goes on with a description such as “it contains a line break at character 41”, the key was pasted with an invisible character or a stray newline: retype the characters around that position. Otherwise check for a typo and that the key wasn’t revoked on the API keys page. Run env | grep ANTHROPIC (PowerShell: Get-ChildItem Env:ANTHROPIC*) too, since direnv, dotenv plugins and IDE terminals can load an old key from a project’s .env. When the API recognises the key but rejects the account or organization behind it, because the key was just revoked or the organization was disabled or removed your access, you get this instead:
Please run /login · API Error: 401 Invalid authentication credentialsCopiedDespite the wording, /login won’t replace an approved key: rotate it in the Console, or unset it to fall back to your plan.
Credit balance is too low
Credit balance too low · Add funds: https://platform.claude.com/settings/billingCopiedThe Console organization behind the key is out of prepaid credit. Buy credits on that page, and consider auto-reload. If you pay for a plan and didn’t mean to use a key at all, the key is the problem, not the balance.
Your organization has disabled API key authentication
A Console admin turned keys off, so the API refuses yours. The text after the · names the source: unset ANTHROPIC_API_KEY or remove apiKeyHelper, then /login with claude.ai, because both outrank a login. Its sibling, Your ANTHROPIC_API_KEY belongs to a disabled organization, means the key comes from a disabled Console organization: unset it, or replace it with a key from an active one.
Your apiKeyHelper script is failing
Your apiKeyHelper script is failing · This usually means you need to re-authenticate with your provider · Run /status to see the script's error outputCopiedThe command exited with an error, timed out, printed nothing, or printed something besides the key. Run it yourself in a shell. It must print only the key, as one token of printable ASCII up to 16,384 characters, and exit 0. In /status, the apiKeyHelper row shows Failing with the exit code and the script’s error output. /login doesn’t help while the setting is there.
Request rejected (429), and the monthly cap
API Error: Request rejected (429) · this may be a temporary capacity issue. If it persists, check https://status.claude.com.CopiedYou hit the rate limit on your key, which the API sets for the whole organization by usage tier. New organizations can start on an Evaluation tier with limits below the standard ones, which rise with usage history; the Rate limits page in the Console shows the current tier. Fewer parallel subagents, or a smaller model for bulk runs, also help. A spending stop looks different on the API’s side, per the rate limits docs: at the tier cap it returns a 429 starting “You have reached your API usage limits” with no retry-after, so retrying fails until the month turns over; at a limit you set, a 400 starting “You have reached your specified API usage limits”.