返回指南
Integration·2026年7月26日·8 min read

Claude Code API key — where to get one, where to put it, and why the wrong variable fails silently

Claude Code takes a subscription login or an API key, and the two behave very differently once set. Here is where each comes from, exactly which variable holds it, and the header mismatch behind most 401s.

Claude Code can authenticate two different ways, and the one you need decides everything else. A claude.ai subscription login covers usage inside your Pro or Max plan. An API key bills per token with no plan limits. This guide covers where to get a key, exactly where to put it, the two credential variables and why choosing the wrong one produces a silent failure, and how to keep the bill under control once it works.

Do you need a key at all?

SituationWhat to use
You have Claude Pro / Max and stay inside the limitsSubscription login — no key needed
No subscription, or you hit limits mid-taskAPI key, billed per token
You want a cheaper per-token rateAPI key from a gateway
Team usage that needs per-seat attributionAPI key per developer

Worth knowing before you start: setting a key parks your subscription. While a credential variable is active, Claude Code uses it instead of a saved claude.ai login, the plan's limits stop applying, and usage bills to whoever owns the key. Unset it and Claude Code goes back to the subscription.

Option 1 — a first-party Anthropic key

  1. Sign in at console.anthropic.com (a separate account from claude.ai).
  2. Add credit under Billing. The API is prepaid and separate from any subscription — a Pro plan does not fund it.
  3. Create a key under API Keys. It starts with sk-ant- and is shown once.
anthropic-key.sh
export ANTHROPIC_API_KEY=sk-ant-...
# Then approve it once, interactively:
#   /config  ->  Use custom API key
claude

Note the second step in that snippet. ANTHROPIC_API_KEY is sent in the x-api-key header and needs a one-time interactive approval before Claude Code will use it. If that prompt was ever declined, the key is ignored afterwards with no prompt at all — which looks exactly like the variable not being read. Re-enable it under /config Use custom API key.

Option 2 — a key that costs less per token

Claude Code reads ANTHROPIC_BASE_URL natively, so it works against any endpoint serving the Anthropic Messages API — no plugin, no proxy, no patched binary. That is the supported path for gateways, and it is how you run the same Claude models at a lower rate:

~/.zshrc
export ANTHROPIC_BASE_URL=https://api.kunavo.com
export ANTHROPIC_AUTH_TOKEN=sk-kn-...
export ANTHROPIC_MODEL=claude-sonnet-4-6
export ANTHROPIC_DEFAULT_HAIKU_MODEL=claude-haiku-4-5

ANTHROPIC_BASE_URL is the origin only — Claude Code appends /v1/messages itself. Create the sk-kn- key in the dashboard after signing up and topping up $5. There's no monthly fee and the balance doesn't expire.

ModelKunavo in / out per 1MUse for
claude-sonnet-4-6$1.20 / $6.00Everyday coding
claude-opus-5$2.00 / $10.00Hard refactors, plan mode
claude-haiku-4-5$0.40 / $2.00Background tasks

That's about 60% under list on the mainline model. Full rates are in the Claude API pricing guide; the full setup, including per-task model routing and what changes behind a gateway, is in the Claude Code router guide.

Where the key actually goes

Two variables, two different HTTP headers. A key in the header the server doesn't read fails with 401:

VariableHeaderUse when
ANTHROPIC_AUTH_TOKENAuthorization: BearerBearer-token keys; takes effect immediately
ANTHROPIC_API_KEYx-api-keyAnthropic Console keys; needs one-time approval
apiKeyHelperBothRotating or vault-held credentials

If you weren't told which kind you have, start with ANTHROPIC_AUTH_TOKEN — on Kunavo it is also the variable that lets Claude Code discover the model list, since /v1/models reads the bearer header only.

Shell export vs settings file

A shell export applies to that terminal and its children only. An editor launched from the dock won't see it, and neither will background agents. For anything permanent, use the env block of ~/.claude/settings.json instead — same keys, applies everywhere Claude Code runs. Don't put a key in a project's .claude/settings.json; that file is committed and shared with everyone who clones the repo.

Run /status to confirm which credential is live. An Auth token or API key line naming your variable means the key is active; a Login method line naming a claude.ai account means it isn't.

Rotating keys without editing files

If the credential expires on a schedule or comes from a vault, point apiKeyHelper at a command that prints the current one:

~/bin/get-key.sh
#!/bin/bash
# Any command that prints the current key to stdout works.
vault kv get -field=api_key secret/claude-code

Reference it as "apiKeyHelper": "~/bin/get-key.sh" in your settings file. Claude Code caches the output for five minutes and re-runs it on a 401; adjust with CLAUDE_CODE_API_KEY_HELPER_TTL_MS. The value is sent in both headers, so it works either way.

Keeping the bill predictable

Agentic coding is token-hungry — every step resends the system prompt, the task history and fresh file context. Four things that matter more than anything else:

  1. Route background work to Haiku. ANTHROPIC_DEFAULT_HAIKU_MODEL=claude-haiku-4-5 covers the summaries and titles Claude Code generates on its own. It's one line and it's pure savings.
  2. Start new tasks rather than extending one forever. Context is resent every step, so a long session is quadratically expensive.
  3. Let prompt caching work. Cached input bills at 10% of the input rate, and the native Messages API route passes cache_control through untranslated (details).
  4. Give the editor its own key with a spend limit in the dashboard, then check usage after a week. Per-key limits turn a runaway loop into a capped one.

Troubleshooting

SymptomFix
401 invalid or unrecognized tokenKey is in the wrong header — swap between the two variables. Or the key was revoked; regenerate it.
Variable set, but Claude Code still asks you to log inSet it somewhere read before first-run setup: a shell export or ~/.claude/settings.json. A project-level settings file applies only after the trust prompt.
ANTHROPIC_API_KEY ignored with no promptPreviously declined. /config Use custom API key.
Startup warning naming two credential sourcesA key and a saved login are both active. Run /logout to use the key, or unset the variable to use the login.
Credit exhausted mid-sessionTop up; see insufficient credit.

FAQ

Is the Claude Code API key the same as my claude.ai login?

No. They're separate systems with separate billing — console.anthropic.com issues API keys, claude.ai handles subscriptions. A Pro plan does not fund API usage.

Can I use one key for Claude, Gemini and GPT?

On Kunavo, yes — the same sk-kn- key serves every model in the catalog. Claude Code itself only speaks the Anthropic Messages API, so within Claude Code you'll be using the Claude models; other tools can use the same key for the rest.

What does a key cost to hold?

Nothing. Kunavo is pay-as-you-go from a $5 top-up with no monthly fee and a balance that doesn't expire — you pay for tokens, not for having a key.

How do I get an API key for the Anthropic API generally?

See the Claude API key doc for the non-Claude-Code case, including SDK setup and key management.