Claude Code API Setup: Use an API Key, Not a Subscription

Zivv••39 min read
On this page
  1. Subscription vs Official API Key vs Gateway
  2. The Environment Variables That Matter
  3. Step 1: Get a Key
  4. Step 2: Set the Variables
  5. Step 3: Verify
  6. Choosing Models
  7. Controlling Spend
  8. Common Errors
  9. Wrap-Up
  10. FAQ

This is the hub page for running Claude Code on API credentials: for people who would rather not buy a subscription, who keep hitting subscription limits, or who want a team billed by actual usage. It compares the three ways to pay for Claude Code, lists the environment variables that matter, then walks through setup, verification, model choice, cost control, and the errors you are most likely to see. Installation and making variables persistent are covered per OS in the macOS and Linux guide and the Windows guide, so they are not repeated here.

Subscription vs Official API Key vs Gateway

Subscription (Pro, Max, and up)Official Anthropic API keyThird-party gateway (e.g. Zivv)
Sign-in/login with a claude.ai accountANTHROPIC_API_KEY, or /login with a Claude Console accountANTHROPIC_BASE_URL + ANTHROPIC_AUTH_TOKEN
BillingMonthly plan with usage windowsPer token, from your Console balancePer token, from your gateway balance
LimitsWait for the window to reset when you run outRate limits by account tierDepends on the gateway's routes and groups
PaymentSubscription chargeConsole creditsWhatever the gateway accepts
Best forSteady usage, no bills to manageTeams already set up with Anthropic billingUnified billing, many models, team budgets

Whether a subscription or metered usage is cheaper depends on how much you use Claude Code; the subscription vs API guide shows how to estimate it. The rest of this article covers the two API-key routes.

One thing to know up front: features tied to a claude.ai login are affected. Anthropic's docs state that Remote Control and voice dictation are unavailable while ANTHROPIC_API_KEY or ANTHROPIC_AUTH_TOKEN is active, and Remote Control is also disabled while ANTHROPIC_BASE_URL points at a non-Anthropic host.

The Environment Variables That Matter

Claude Code reads the following (see the official environment variable reference for the authoritative list):

VariableWhat it doesOfficial keyGateway
ANTHROPIC_BASE_URLWhere requests goLeave unsetRequired; https://zivv.pro for Zivv
ANTHROPIC_AUTH_TOKENCredential sent as Authorization: BearerLeave unsetYour gateway key
ANTHROPIC_API_KEYCredential sent as X-Api-KeyYour official keyUsually unset
ANTHROPIC_MODELModel used at startupOptionalOptional
ANTHROPIC_DEFAULT_OPUS_MODEL and siblingsPoint the opus, sonnet, haiku, and fable aliases at specific model IDsOptionalOptional
ANTHROPIC_DEFAULT_HAIKU_MODELThe haiku alias, also used for background work such as session titlesOptionalWorth pointing at a low-cost model
CLAUDE_CODE_SUBAGENT_MODELDefault model for subagentsOptionalOptional
ANTHROPIC_CUSTOM_HEADERSExtra request headers in Name: Value formatOptionalWhen the gateway asks for one

ANTHROPIC_AUTH_TOKEN vs ANTHROPIC_API_KEY

The difference is the header. ANTHROPIC_AUTH_TOKEN goes into Authorization with a Bearer prefix; ANTHROPIC_API_KEY goes into X-Api-Key. Anthropic's guidance: use ANTHROPIC_API_KEY for direct API access with a key from the Claude Console, and ANTHROPIC_AUTH_TOKEN when routing through a gateway or proxy that authenticates with bearer tokens.

Two behaviors are worth knowing:

  • Precedence: when several credentials are present, ANTHROPIC_AUTH_TOKEN wins over ANTHROPIC_API_KEY, and both win over a subscription login saved by /login
  • Approval prompt: in interactive mode Claude Code asks once whether to use an ANTHROPIC_API_KEY and remembers your answer; ANTHROPIC_AUTH_TOKEN takes effect without a prompt

Zivv accepts either header, but its docs standardize on ANTHROPIC_AUTH_TOKEN because it is the easiest to reason about. Do not set both at once, or you will not know which key is in use.

No /v1 in the base URL

Claude Code appends /v1/messages to the base URL itself, so ANTHROPIC_BASE_URL is just the root domain, https://zivv.pro. Setting https://zivv.pro/v1 produces /v1/v1/messages, which fails (Zivv answers that path with 405 Method Not Allowed; other gateways usually return 404). The /v1 address is for OpenAI-protocol clients such as Codex and Cursor.

Step 1: Get a Key

Official API key: create one in the Claude Console (platform.claude.com) and add credits. Alternatively, skip the manual key: run claude, use /login, and choose a Console account.

Zivv key:

  1. Sign up, open the API keys page in the console, and click Create key
  2. Pick the Claude MAX model group: it is built for Claude Code, Claude Desktop, and the Anthropic SDKs and accepts the native Anthropic protocol only. If the same key also has to work in Cursor or the OpenAI SDK, pick Claude Max Full, which has no client restriction. The two groups have different multipliers; check the model pages in the Model Hub, and see the account pool guide for how the pool works
  3. Optionally set a spending limit (the most this key can ever spend) and a per-task limit (the most one Claude Code session can spend), both covered below
  4. Copy the key, which starts with sk-

Use one key per device or purpose so usage stays readable and a lost laptop costs you one key, not all of them.

Step 2: Set the Variables

macOS and Linux

Export for the current terminal first and make it persistent only once it works:

export ANTHROPIC_BASE_URL=https://zivv.pro
export ANTHROPIC_AUTH_TOKEN=sk-your-key-here
claude

With an official key you need one variable, and no leftover base URL:

unset ANTHROPIC_BASE_URL
export ANTHROPIC_API_KEY=sk-ant-your-key-here
claude

Which shell profile to edit and how to avoid npm permission errors are in the macOS and Linux guide.

Windows PowerShell

$env:ANTHROPIC_BASE_URL = "https://zivv.pro"
$env:ANTHROPIC_AUTH_TOKEN = "sk-your-key-here"
claude

Persisting with setx and WSL caveats are in the Windows guide.

settings.json on any OS

To scope the configuration to Claude Code only, put it in the env block of ~/.claude/settings.json (%USERPROFILE%\.claude\settings.json on Windows):

{
  "env": {
    "ANTHROPIC_BASE_URL": "https://zivv.pro",
    "ANTHROPIC_AUTH_TOKEN": "sk-your-key-here",
    "ANTHROPIC_DEFAULT_HAIKU_MODEL": "claude-haiku-5-5"
  }
}

Two details. When the same variable is set in both the shell and a settings file, the settings file wins, so check it first when a changed variable seems to have no effect. And never put a key in a project's .claude/settings.json, which is committed to Git; use .claude/settings.local.json for per-project keys. If you manage several configurations with CC Switch, the Zivv API keys page can import a key's config into it in one click.

VS Code extension

Anthropic's docs configure the extension through claudeCode.environmentVariables in your VS Code user settings (JSON):

{
  "claudeCode.environmentVariables": [
    { "name": "ANTHROPIC_BASE_URL", "value": "https://zivv.pro" },
    { "name": "ANTHROPIC_AUTH_TOKEN", "value": "sk-your-key-here" }
  ]
}

Step 3: Verify

Work through these in order and stop at the first failure:

  1. Test the address and key without Claude Code: send the minimal Messages request below; a JSON response means both are fine
  2. One non-interactive call: claude -p "Reply OK" returning text means Claude Code picked up the variables
  3. Check /status: inside claude, the "Anthropic base URL" line should show https://zivv.pro and the credential line should name ANTHROPIC_AUTH_TOKEN; a claude.ai login there means the variables never reached the session
  4. Check the console: the request should appear in Zivv's usage logs with its time, model, and cost, which proves traffic actually went through the gateway

The request for step 1:

curl https://zivv.pro/v1/messages \
  -H "Authorization: Bearer sk-your-key-here" \
  -H "anthropic-version: 2023-06-01" \
  -H "Content-Type: application/json" \
  -d '{"model":"claude-sonnet-5-5","max_tokens":16,"messages":[{"role":"user","content":"ping"}]}'

If curl returns 401, the key itself is the problem; if curl works but Claude Code fails, the variables are not reaching Claude Code.

If you previously signed in with a subscription and startup warns about two credential sources (older versions say Auth conflict: Both a token ... and an API key ... are set), run /logout to drop the saved login, or unset the variable you do not want.

Choosing Models

Switch any time with /model, or pin defaults with variables before launch. Using Model Hub prices at the time of writing, the relative input prices of the four recommended versions are roughly:

Model IDRelative input priceGood for
claude-haiku-5-51Background work like session titles, small edits, bulk chores
claude-sonnet-5-54Everyday coding and tests; the sensible default
claude-opus-5-58Architecture, cross-module refactors, hard bugs
claude-fable-5-216Problems Sonnet and Opus cannot crack, long unattended runs

A common setup:

export ANTHROPIC_MODEL=claude-sonnet-5-5
export ANTHROPIC_DEFAULT_OPUS_MODEL=claude-opus-5-5
export ANTHROPIC_DEFAULT_HAIKU_MODEL=claude-haiku-5-5

Sonnet is the default, /model opus resolves to the Opus version you chose, and background tasks run on Haiku. Note that with ANTHROPIC_MODEL set, every launch returns to that model; a /model choice lasts for the session.

Three more points:

  • Version requirements: Anthropic's docs list Claude Code v2.1.284 or later for Sonnet 5.5, v2.1.280 or later for Opus 5.5, and v2.1.293 or later for Haiku 5.5. Older versions fail with Claude Code does not support this model; run claude update
  • Exact IDs: copy them from the Model Hub or GET /v1/models; a typo usually returns 404
  • Non-Claude models: Zivv can also serve models such as DeepSeek over the Anthropic protocol (guide), but Anthropic states it does not support routing Claude Code to non-Claude models through any gateway, so tool use and other behavior may differ; trial it on low-stakes work first

The Claude model comparison goes deeper on each family.

Controlling Spend

The fear with metered billing is one long task quietly running up a large bill. Defend in layers:

LayerHowEffect
One sessionPer-task limit on the Zivv keyWhen a Claude Code session reaches the limit, its next request gets a 402 and Claude Code stops with the reason; a new session starts fresh
One keySpending limit on the keyRequests are refused once the key's total spend hits the cap, so a leaked key has a ceiling
TeamTeam budgets and per-member keys in TeamsUsage split by member, with a cap on the whole team
HabitsRight model for the task, regular /clear and /compactFewer tokens in the first place

You can also set a cap from the client for a single run, handy for one big job:

export ANTHROPIC_CUSTOM_HEADERS="X-Zivv-Task-Budget: 5"
claude

The header can only tighten the key's or team's limit, never loosen it, and uses the same unit as your balance. Requests under a cap come back with X-Zivv-Task-Spent and X-Zivv-Task-Budget response headers.

Know where the real numbers live. The Session section of Claude Code's /usage shows a cost that Claude Code estimates locally from official list prices; it is not what the gateway charged. On Zivv the authoritative figures are in the console: usage logs list every request, and the Task spend page groups a Claude Code session's requests into one task with its total, the models used, and the difference from official pricing.

For token-saving tactics see Claude Code token saving tips and the prompt caching guide; for team key and budget design, see team API key and budget practices.

Common Errors

Symptom or messageUsual causeFix
API Error: 401 or Invalid API keyKey truncated or deleted, or the credential is in the wrong variableRe-copy the key; gateways use ANTHROPIC_AUTH_TOKEN. See the 401 fix
Startup warning about two credential sourcesA subscription login and an environment key are both active/logout, or unset the variable you do not want
402, insufficient balanceBalance empty, key limit reached, or per-task limit hitTop up or raise the limit; for a task limit, start a new session. See the 402 fix
403The key's group does not include the model, or the group restricts clientsSwitch group; see the 403 guide
404 or 405Base URL ends in /v1, or the model ID is wrongUse https://zivv.pro and check the ID; see the 404 guide
429, Request rejected (429), constant throttlingSubscription windows or account rate limits, or too much concurrencySee Claude Code rate limit solutions
Streaming response ended before any complete data was receivedA proxy or gateway in the path is not passing the stream through unmodifiedSee the streaming response fix
529 Overloaded, timeoutsUpstream overload or oversized requestsRetry later and split large tasks; see 529 and timeouts
Claude Code does not support this modelClaude Code is older than the model requiresclaude update
Unable to connect to APIWrong address, or a network or proxy blockGet the curl test above working first
400 Extra inputs are not permittedThe gateway's upstream rejects experimental fields Claude Code sendsAnthropic's docs suggest CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS=1

For anything else, read the full error text: behind a gateway, the message after a 401 comes from the gateway rather than Anthropic. The official error reference and Zivv's error codes cover most cases.

Wrap-Up

Running Claude Code on an API key takes two variables: ANTHROPIC_API_KEY for an official key, or ANTHROPIC_BASE_URL plus ANTHROPIC_AUTH_TOKEN for a gateway. Verify with curl, claude -p, /status, and the console's usage log, pin your default models, and let key limits and per-task budgets cap the downside. To try metered Claude Code, create a Zivv key in the Claude MAX group and you can be running in minutes; other coding tools are covered on the vibe coding page.

FAQ

Can I use Claude Code without a Claude Pro or Max subscription?

Yes. Claude Code authenticates with API credentials and bills per token: set ANTHROPIC_API_KEY or sign in with a Claude Console account for direct access, or set ANTHROPIC_BASE_URL and ANTHROPIC_AUTH_TOKEN for a gateway. The main functional difference is that features tied to a claude.ai login, such as Remote Control and voice dictation, are unavailable; coding, running commands, and MCP work the same.

Should I use ANTHROPIC_AUTH_TOKEN or ANTHROPIC_API_KEY?

It depends on where the key came from. A key from Anthropic's Claude Console goes in ANTHROPIC_API_KEY, sent as X-Api-Key. A key issued by a gateway or proxy usually goes in ANTHROPIC_AUTH_TOKEN, sent as Authorization: Bearer, which also takes precedence. Zivv accepts both headers but recommends ANTHROPIC_AUTH_TOKEN. Do not set both.

I set the variables, but Claude Code still asks me to log in or uses my subscription. Why?

The variables are not reaching the Claude Code process. Echo them in the same terminal you launch claude from, then check /status for an "Anthropic base URL" line and an environment-variable credential. Typical causes are editing the profile of a different shell, not opening a new terminal, or an old value in a settings.json env block overriding the shell. If you were previously signed in with a subscription, run /logout and restart.

Why doesn't /usage match what the gateway charged?

The Session section of /usage is estimated locally by Claude Code from official list prices; it knows nothing about your gateway's pricing. Through Zivv, each request costs the official price times the group multiplier, and the authoritative numbers are in the console's usage logs and on the Task spend page, which totals each Claude Code session as one task.

Could a gateway swap the model behind Claude Code?

Start by running /model to confirm which model the session uses; Claude Code itself does not silently change model versions. On the gateway side, Zivv lets you pass a response's X-Request-ID to /v1/generation to see the final model, tokens, and cost for that request. To compare answer quality systematically, run a fixed prompt set against the official API and the gateway, as described in the model downgrade test.