Skip to main content

Claude Code API Configuration: Keys, Settings, Models, and Gateways

A
13 min readClaude Code

A route-first Claude Code configuration guide for ANTHROPIC_API_KEY, ANTHROPIC_AUTH_TOKEN, ANTHROPIC_BASE_URL, settings files, model priority, provider routes, and safe verification.

Claude Code API Configuration: Keys, Settings, Models, and Gateways

Claude Code API configuration starts with route choice, not with pasting a key. Before you set ANTHROPIC_API_KEY, edit settings.json, or point Claude Code at a gateway, decide which route should own this session: subscription login, direct Anthropic API key, bearer-token gateway, dynamic helper, Bedrock, Vertex, or Foundry.

Claude Code API configuration route board

The safe order is route, scope, model, verification. Use shell variables or local-only settings for secrets, shared project settings for team behavior, /model or --model for scoped model changes, and /status before you trust the session.

Intended setupConfigure hereFirst verification
Normal interactive Claude CodeSubscription login and user/project settings/status should show the expected account route
Direct Anthropic API keyLocal shell env or local-only settings with ANTHROPIC_API_KEY/status plus an environment check
Compatible gateway or proxyANTHROPIC_AUTH_TOKEN plus ANTHROPIC_BASE_URL in a local scopeVerify base URL, model name, and gateway trust boundary
Bedrock, Vertex, or FoundryProvider credentials and provider route variablesConfirm provider route and model name before real work

Choose The Claude Code Route Before You Configure Anything

Claude Code can look like one tool while actually running through several different contracts. The route decides which credential is active, which account or provider owns the session, which settings matter, and which bill or usage meter you should read. A copied setup command is not safe until the route is intentional.

The normal interactive route is subscription login. Use it when you are running Claude Code as a human developer in a terminal and want the session tied to your Claude account. This is the sibling of install and plan setup, not an API-key requirement. If your question is still "how do I install and launch the CLI?", use the Claude Code install guide first.

The direct API route is ANTHROPIC_API_KEY. Use it when the session should deliberately use an Anthropic Console API key, such as a CI run, scripted agent, headless task, evaluation harness, or a local workflow you want billed and tracked as API usage. If your uncertainty is who pays for a session after an API key is present, route that decision to the Claude Code API key vs subscription billing guide.

The compatible gateway route is ANTHROPIC_AUTH_TOKEN plus ANTHROPIC_BASE_URL. Use it only when you understand the gateway's trust boundary, model naming, header behavior, and compatibility with Anthropic Messages, Bedrock InvokeModel, or Vertex rawPredict style APIs. A gateway can be useful infrastructure, but it is not the same contract as direct Anthropic API access.

Provider routes such as Bedrock, Vertex, and Foundry are separate again. They use provider credentials and provider-specific route variables. Once a provider owns authentication, normal /login assumptions no longer explain the session.

As of the official-doc check on April 21, 2026, the practical decision board is:

RouteBest forAvoid when
Subscription loginNormal interactive coding with a Claude accountYou need a service account, CI, or API ledger
ANTHROPIC_API_KEYDirect Anthropic API usage through Claude CodeYou expect subscription usage to cover it automatically
ANTHROPIC_AUTH_TOKEN + ANTHROPIC_BASE_URLA compatible gateway with a clear trust contractThe gateway cannot preserve required headers or model names
apiKeyHelperManaged key retrieval for terminal CLI sessionsYou need Claude Desktop or remote-session OAuth behavior
Bedrock, Vertex, FoundryEnterprise cloud-provider routingYou expect /login and /logout to behave like normal Claude Code auth

Credential Precedence: What Wins In Claude Code

Claude Code credential precedence ladder

Credential precedence is the part most setup guides bury. Claude Code does not simply use the last thing you remember configuring. It resolves the active route from a priority ladder, so a stale environment variable or provider credential can make a new settings edit look broken.

The current priority order in Anthropic's Claude Code authentication documentation is: cloud provider credentials first, then ANTHROPIC_AUTH_TOKEN, then ANTHROPIC_API_KEY, then apiKeyHelper, then OAuth token, then /login subscription credentials. Treat that as a runtime fact to verify, not as background trivia.

That order has direct consequences:

If this is presentWhat can happenSafe move
Provider credentials and provider flagsBedrock, Vertex, or Foundry can own the sessionConfirm provider route before changing Anthropic keys
ANTHROPIC_AUTH_TOKENBearer-token gateway route can win over a direct API keyCheck base URL and gateway contract together
ANTHROPIC_API_KEYDirect API route can override subscription expectationsVerify /status and API billing owner
apiKeyHelperA helper can retrieve credentials for terminal CLI sessionsAudit helper output and access controls
OAuth or /login onlyNormal Claude Code login can own the sessionUse account and subscription checks

When a session surprises you, do not rotate keys first. Ask which higher-priority credential is present. A direct shell check should avoid printing secret values:

bash
test -n "$ANTHROPIC_AUTH_TOKEN" && echo "ANTHROPIC_AUTH_TOKEN is set" test -n "$ANTHROPIC_API_KEY" && echo "ANTHROPIC_API_KEY is set" printenv ANTHROPIC_BASE_URL

If the route is not the one you intended, remove the higher-priority variable from the current shell, terminal profile, project launcher, devcontainer, or CI secret store. Then start a new Claude Code session and run /status again.

Settings Scopes: Which File Should You Edit?

Claude Code settings scope map

Claude Code settings are hierarchical. Editing the wrong file is how secrets leak into a repository or team settings fail to apply. The safe rule is narrowest scope first: put shared behavior in shared project settings, personal behavior in user settings, and secrets or machine-only overrides in local-only or shell-controlled scopes.

Current Claude Code settings precedence is managed settings, command-line arguments, local project settings, shared project settings, then user settings. Environment variables and auth credentials are not a substitute for understanding those scopes; they are another layer that can affect runtime behavior.

ScopeTypical path or surfaceUse it forDo not use it for
Managed settingsEnterprise-managed configOrganization policy, locked behaviorPersonal experiments
Command-line argumentsclaude --model ... or one-shot flagsTemporary session controlDurable team defaults
Local project settings.claude/settings.local.jsonPersonal machine overrides and local-only secretsFiles that should be committed
Shared project settings.claude/settings.jsonTeam behavior, permissions, shared non-secret defaultsAPI keys, bearer tokens, private URLs
User settings~/.claude/settings.jsonPersonal defaults across projectsTeam-specific policy
Shell environmentCurrent shell, profile, CI, devcontainerCredentials and route flagsHidden defaults nobody can audit

Use JSON settings for behavior. Use environment variables or local-only secret stores for credentials. A shared .claude/settings.json can be valuable for permissions and team conventions, but it should not become a credential locker.

A safe project pattern looks like this:

json
{ "permissions": { "allow": ["Bash(npm test)", "Bash(npm run lint)"], "deny": ["Bash(rm -rf *)"] } }

That belongs in shared project settings because it teaches Claude Code how the repository should be handled. An API key does not belong there. Put credentials in the local shell, CI secret storage, or .claude/settings.local.json only when the file is ignored and truly machine-local.

Direct Anthropic API Key Setup

Use ANTHROPIC_API_KEY when you want Claude Code to run through a direct Anthropic API key. This is the clean route for API-led automation, not a magic upgrade to a subscription session. The key should come from Anthropic Console and should be controlled like any production credential.

For a temporary local session, prefer a shell variable that disappears when the shell closes:

bash
export ANTHROPIC_API_KEY="$YOUR_ANTHROPIC_API_KEY" claude /status

For a one-command test that avoids putting the key into a profile:

bash
ANTHROPIC_API_KEY="$YOUR_ANTHROPIC_API_KEY" claude

For CI or repeatable automation, use the CI platform's secret manager instead of committing a key to the repository. Then add a verification step that checks route presence without echoing the value:

bash
test -n "$ANTHROPIC_API_KEY" || { echo "ANTHROPIC_API_KEY is missing" exit 1 }

After the session starts, run /status and confirm that the active route matches the API-key path you intended. If the same machine is also used for subscription login, do not assume the interactive route survived the API-key export. Credential precedence can move the session onto API usage.

If you are still deciding whether you can get a key without paying, read the Claude API key free tier guide separately. Once a route exists, the configuration job is to make that route explicit, narrow, and verifiable.

Gateway Or Proxy Setup

A gateway setup has two moving parts: the token and the base URL. ANTHROPIC_AUTH_TOKEN is sent as a bearer token, while ANTHROPIC_BASE_URL changes the host Claude Code talks to. Those variables should be treated as a pair because the token is only meaningful inside the trust boundary of the service receiving it.

bash
export ANTHROPIC_AUTH_TOKEN="$YOUR_GATEWAY_TOKEN" export ANTHROPIC_BASE_URL="https://gateway.example.com" claude /status

Do not call a gateway compatible just because it accepts a token. Claude Code's gateway documentation expects the service to expose compatible API shapes and preserve required version and beta headers. Model names may also need explicit environment variables because gateway aliases can differ from Anthropic's direct API names.

Gateway setup should pass four checks before real work:

CheckWhy it matters
Base URL is intentionalPrevents silently sending requests to the wrong host
Bearer token belongs to that gatewayPrevents cross-service credential confusion
Model names resolve correctlyPrevents a session from using the wrong model or failing late
Header behavior is preservedPrevents partial compatibility from breaking tools or beta features

Claude Code also treats non-first-party hosts differently for some tool-search behavior. Do not flip safety-related switches casually; enable only what your gateway contract and data boundary justify.

If your real decision is which gateway route to buy or operate, use the Claude gateway guide. Keep vendor selection separate from basic Claude Code configuration so you can evaluate price, reliability, data handling, and compatibility on their own merits.

One security warning belongs directly in this section: Anthropic's gateway documentation called out compromised LiteLLM versions 1.82.7 and 1.82.8 and states that Anthropic does not endorse or audit LiteLLM. That does not mean every gateway is unsafe. It does mean gateway credentials deserve stricter version, source, and logging checks than a casual local setting.

Model Configuration Ladder

Model selection has its own precedence ladder. If the model in /status or /model does not match what you expected, look at every layer before assuming Claude Code ignored you.

The current model priority order is /model, startup --model, ANTHROPIC_MODEL, then model in settings. That means an interactive /model choice can beat a settings default, and a startup flag can beat an environment variable.

NeedBest surfaceExample
Change the current interactive session/modelUse inside Claude Code when testing one task
Start one session with a chosen model--modelclaude --model sonnet
Set a shell-level defaultANTHROPIC_MODELexport ANTHROPIC_MODEL="sonnet"
Set a durable defaultmodel in settingsUser or project settings, depending on ownership
Use provider-specific routingFull provider model name or provider default variableBedrock, Vertex, or Foundry model identifiers

As of April 21, 2026, Anthropic's model configuration docs say opus and sonnet aliases on the Anthropic API resolve to current model families, while cloud-provider aliases may lag behind direct Anthropic defaults. That is exactly the kind of fact that should be checked when precision matters. For important workflows, pin the provider-specific model name instead of relying on a short alias forever.

Use this reset pattern when the model seems wrong:

bash
/model printenv ANTHROPIC_MODEL claude --model sonnet

If /model shows the right value but behavior still looks wrong, verify the route next. A gateway or provider route can impose model-name rules that a direct Anthropic API example does not cover.

Bedrock, Vertex, And Foundry Routes

Provider routes are not just alternative base URLs. They hand authentication and model resolution to a cloud provider or platform. That changes the setup surface and changes which failure messages matter.

For Amazon Bedrock, the official Claude Code route uses a provider flag and AWS region:

bash
export CLAUDE_CODE_USE_BEDROCK=1 export AWS_REGION="us-east-1" claude /status

Your AWS credentials must already be valid for the Bedrock models you intend to use. When Bedrock handles authentication, /login and /logout are not the normal control points for that session.

For Google Vertex AI, the route is similar in shape but uses Google Cloud credentials plus Vertex variables:

bash
export CLAUDE_CODE_USE_VERTEX=1 export CLOUD_ML_REGION="us-central1" export ANTHROPIC_VERTEX_PROJECT_ID="$YOUR_GCP_PROJECT_ID" claude /status

Use provider documentation for the final credential grant, region, quota, and model-name details. Claude Code can route the session, but the cloud provider owns access, IAM, regional availability, and billing.

Foundry follows the same category of decision: provider route first, provider credentials second, Claude Code verification third. Do not mix a provider setup with a direct API-key mental model. The test is simple: if provider credentials own the session, verify the provider route and provider model name before you start real work.

Verification Checklist

Claude Code API configuration verification checklist

Trust verified state, not remembered state. The minimum verification loop is route, scope, model, and secret exposure.

Run these inside Claude Code:

text
/status /config /model

Run these in the shell without printing secrets:

bash
test -n "$ANTHROPIC_API_KEY" && echo "ANTHROPIC_API_KEY is set" test -n "$ANTHROPIC_AUTH_TOKEN" && echo "ANTHROPIC_AUTH_TOKEN is set" printenv ANTHROPIC_BASE_URL printenv ANTHROPIC_MODEL printenv CLAUDE_CODE_USE_BEDROCK printenv CLAUDE_CODE_USE_VERTEX

Interpret the result with this board:

SymptomLikely causeNext move
/status shows API route but you expected loginANTHROPIC_API_KEY or higher-priority credential is presentRemove the variable from shell/profile/CI and restart
Gateway URL appears unexpectedlyANTHROPIC_BASE_URL is setAudit shell, project launcher, and local settings
Model is not the one in settings/model, --model, or ANTHROPIC_MODEL has higher priorityClear higher-priority selector or make it intentional
Provider route owns the sessionBedrock, Vertex, or Foundry variables are activeVerify provider credentials, region, quota, and model name
Team settings do not applyLocal or managed settings outrank shared project settingsInspect /config and move the setting to the right scope

If you need to return to a clean subscription-login route in the current terminal, remove route variables and start fresh:

bash
unset ANTHROPIC_API_KEY unset ANTHROPIC_AUTH_TOKEN unset ANTHROPIC_BASE_URL unset ANTHROPIC_MODEL unset CLAUDE_CODE_USE_BEDROCK unset CLAUDE_CODE_USE_VERTEX claude /status

That does not delete keys from Anthropic Console, a gateway, AWS, or Google Cloud. It only clears the current shell. If variables reappear, they are coming from a profile, .env loader, devcontainer, CI config, shell plugin, or project script.

Security And Shared-Repo Hygiene

Claude Code configuration is powerful because it can combine credentials, tools, model selection, and project permissions. That same power makes sloppy storage risky.

Keep these rules:

  • Do not commit API keys, bearer tokens, gateway tokens, provider credentials, or private base URLs.
  • Do not put secrets in .claude/settings.json, because that file is designed for shared project behavior.
  • Do not print keys in debugging output or screenshots.
  • Do not use realistic example keys in docs, tickets, or README files.
  • Do not let a gateway token travel to a host you have not audited.
  • Do not treat model aliases as permanent promises.
  • Do not use subscription-login assumptions when provider variables are active.

For shared project settings, commit only behavior that teammates should inherit: allowed commands, denied commands, permission defaults, and non-secret conventions. For local secrets, prefer shell session variables, OS keychain tooling, CI secret stores, or local-only files that the repository ignores.

Before committing any Claude Code configuration change, run:

bash
git status --short git diff -- .claude/settings.json .claude/settings.local.json

If a secret appears in the diff, stop and rotate it. Removing it from git history after the fact is slower and less reliable than never committing it.

Configuration should not absorb every adjacent Claude Code decision. Use the sibling guides when the job changes:

If your real question is...Read this
How do I install Claude Code on this machine?How to install Claude Code
Does an API key change billing or subscription usage?Claude Code API key vs subscription billing
Can I get an API key or free trial access?Claude API key free tier
Which gateway route should I use?Claude gateway route guide
Why did I hit usage limits?Claude Code usage limit issues

The configuration rule stays the same across those decisions: choose the route, put settings in the narrowest safe scope, set the model at the right priority, then verify with /status, /config, and /model.

FAQ

Do I need an API key to use Claude Code?

Not always. Normal interactive Claude Code use can run through subscription login. Use ANTHROPIC_API_KEY only when you intentionally want the direct API route, such as CI, automation, scripted use, or API-led billing.

Where should I put ANTHROPIC_API_KEY?

Use a shell variable, CI secret store, OS credential manager, or local-only ignored file. Do not put it in shared .claude/settings.json. After setting it, run /status to confirm the active route.

What is ANTHROPIC_AUTH_TOKEN for?

ANTHROPIC_AUTH_TOKEN is sent as a bearer token. In Claude Code gateway setups it is commonly paired with ANTHROPIC_BASE_URL. Treat that pair as a gateway trust contract, not as a direct Anthropic API key.

Can I change the Claude Code base URL?

Yes, ANTHROPIC_BASE_URL can point Claude Code at a compatible gateway or proxy route. Verify the host, token, model names, header behavior, and data boundary before using it for real work.

Which Claude Code settings file should my team commit?

Commit .claude/settings.json only for shared, non-secret behavior. Keep user preferences in ~/.claude/settings.json and local machine overrides or secrets out of shared git history.

How do I pin the model?

Use /model for the current interactive session, --model for one launch, ANTHROPIC_MODEL for a shell default, or the model setting for durable defaults. Provider routes may need provider-specific model names.

Why does Claude Code ignore my login after I set a key?

It probably is not ignoring login; a higher-priority credential may be active. Check provider variables, ANTHROPIC_AUTH_TOKEN, ANTHROPIC_API_KEY, and apiKeyHelper, then restart Claude Code and run /status.

Are Bedrock and Vertex configured like direct Anthropic API keys?

No. Bedrock and Vertex are provider routes. They use provider credentials, regions, project or account settings, and provider-specific model availability. Verify the provider route before relying on direct API-key examples.

What should I check first when Claude Code uses the wrong route?

Run /status, then check environment variables without printing secrets. Remove unintended higher-priority credentials, restart the terminal session, and run /status again before changing plans, gateways, or model settings.

Share:

laozhang.ai

One API, All AI Models

AI Image

Gemini 3 Pro Image

$0.05/img
80% OFF
AI Video

Sora 2 · Veo 3.1

$0.15/video
Async API
AI Chat

GPT · Claude · Gemini

200+ models
Official Price
Served 100K+ developers
|@laozhang_cn|Get $0.1