How to Get a Claude API Key: Console Setup, Key Types, and Common Mistakes
Most people searching for a Claude API key hit one of three walls: they assume their claude.ai subscription includes API access, they cannot complete billing setup, or they have a key that returns 401 because the wrong header is being sent. These are different problems with different fixes.
Your claude.ai subscription is not API access
This is the single most common misunderstanding, and it wastes the most time.
| claude.ai subscription | Anthropic API | |
|---|---|---|
| Where it works | Web and mobile chat interface | Your own code |
| Billing | Monthly subscription | Prepaid, per-token usage |
| Does one include the other | No | No |
| Where you manage it | claude.ai settings | console.anthropic.com |
They are separate account systems with separate balances. A Pro or Max subscription gives you nothing on the API side, and API credit gives you nothing in the chat interface.
If you are writing code, you need the API. If you want to chat in a browser, you do not need a key at all.
Where the key actually lives
API keys are created in the Anthropic Console at console.anthropic.com, not in claude.ai. The flow is: create an organisation, add a payment method, purchase credit, then create a key under API Keys.
Two things catch people out.
The key is shown once. After you close the dialog, the full value is never displayed again. Store it immediately in a password manager or your secrets store. If you lose it, delete it and create a new one — there is no recovery flow.
Credit must be purchased before the key works. A key on an account with zero balance authenticates, and then every request fails on billing. If you get a key and immediately see errors, check the balance before you start debugging your code.
Key types and which header to send
Anthropic's API expects the key in the x-api-key header, not Authorization: Bearer.
curl https://api.anthropic.com/v1/messages \
-H "x-api-key: $ANTHROPIC_API_KEY" \
-H "anthropic-version: 2023-06-01" \
-H "content-type: application/json" \
-d '{"model":"claude-sonnet-5","max_tokens":64,
"messages":[{"role":"user","content":"Hello"}]}'
Model IDs change between generations. Check the model list in your Console — or GET /v1/models — rather than copying an ID out of a blog post, including this one.
The anthropic-version header is required. Omitting it returns an error that does not obviously point at the missing header, which makes it a reliable time sink.
Where this gets confusing: Claude Code reads two different environment variables that send different headers.
| Variable | Header sent |
|---|---|
ANTHROPIC_API_KEY | x-api-key |
ANTHROPIC_AUTH_TOKEN | Authorization: Bearer |
If both are set, one takes precedence and you may be sending a header the endpoint does not accept. When a key works in curl but not in Claude Code, check which of these is set and clear the one you do not want.
The same mismatch is the most common cause of 401s when pointing Claude Code at a gateway — see configuring Claude Code against a compatible endpoint (in Chinese).
Scoping keys so a leak is survivable
Treat every key as something that will eventually leak, and design for that.
- One key per project or service. When you need to revoke, you revoke one thing.
- Set spend limits at the organisation level. A retry loop with no ceiling can burn a lot of credit quickly.
- Never put a key in client-side code. Anything shipped to a browser or a mobile app is public, regardless of obfuscation.
- Never commit a key. Use environment variables or a secrets manager, and add a pre-commit hook or secret scanner.
- Rotate after any exposure. If a key appeared in a screenshot, a log, a support ticket, or a public repository, revoke it rather than hoping nobody noticed.
If a key has been exposed, revocation is the only reliable fix. Rate limits and IP restrictions reduce blast radius but do not replace rotation. A fuller treatment is in our API key security guide (in Chinese).
When you cannot complete billing
Anthropic's billing runs through a payment processor that validates the card against the billing address and issuing region. If you cannot get past that check, there are a few paths, each with real trade-offs.
| Approach | What you control | Trade-off |
|---|---|---|
| Virtual card service | You open the card, you fund it, the Anthropic account stays yours | Card issuance and top-up fees; some card ranges get declined |
| Cloud marketplace (Bedrock, Vertex) | Billing through a cloud provider you can already pay | Different SDK, different model IDs, different quotas |
| OpenAI- or Messages-compatible gateway | Ordering and verification; the upstream account belongs to the provider | Service fee, plus an additional party that can see your requests |
| Buying someone's account | Almost nothing | The account is not yours and can be reclaimed; not recommended |
The cloud marketplace route is worth a serious look if you already have an AWS or Google Cloud account. Model availability and IDs differ, but billing is consolidated with infrastructure you already pay for, and the account is unambiguously yours.
The last row is listed for completeness, not as an option. An account you did not create can be reclaimed through the original owner's recovery flow, and you have no standing to contest it.
If you use a gateway, verify these four things
A gateway sits between your code and the model. That is a real dependency, so check it the way you would check any vendor.
Protocol coverage
Claude Code and the Anthropic SDKs speak the Messages protocol. Some gateways only implement an OpenAI-compatible layer and translate between the two. Translation tends to break on tool-call structures, on system prompt placement, and on streaming event types.
Send a native streaming Messages request and confirm you get message_start, content_block_start, content_block_delta, content_block_stop, message_delta and message_stop. If all you see is a simplified text delta, translation is happening.
Model identity
The model ID is a string the gateway chooses. Cross-check it: send a parameter value the real model rejects and read the upstream error, which often names the actual model. Compare the usage structure against what that model generation returns.
Concrete techniques are in how to verify a relay’s models (in Chinese).
Billing detail
You need per-request token counts split into input, output, cache read and cache write; the charge for that request; and exportable history. Cache-read pricing deserves specific attention, because in long conversations cached tokens can exceed fresh input tokens by a wide margin.
How multipliers and cache pricing interact is covered in relay pricing and multipliers (in Chinese).
Data handling
The gateway can see everything you send, including source code. Confirm whether request bodies are logged, for how long, whether anything is used for training, and whether the upstream is the official API or yet another intermediary.
A full checklist for choosing between gateways is in nine verifiable criteria for picking a Claude Code gateway (in Chinese).
Verifying a key before you build on it
Five requests, in this order. Stop at the first failure.
KEY="your-key"; BASE="https://api.anthropic.com/v1"
# 1. Minimal request
curl -s -o /dev/null -w "%{http_code}\n" "$BASE/messages" \
-H "x-api-key: $KEY" -H "anthropic-version: 2023-06-01" \
-H "content-type: application/json" \
-d '{"model":"claude-sonnet-5","max_tokens":16,"messages":[{"role":"user","content":"hi"}]}'
# 2. Streaming completes properly
curl -sN "$BASE/messages" -H "x-api-key: $KEY" \
-H "anthropic-version: 2023-06-01" -H "content-type: application/json" \
-d '{"model":"claude-sonnet-5","max_tokens":64,"stream":true,
"messages":[{"role":"user","content":"count to three"}]}' | tail -3
# 3. Tool use returns the right stop reason
curl -s "$BASE/messages" -H "x-api-key: $KEY" \
-H "anthropic-version: 2023-06-01" -H "content-type: application/json" \
-d '{"model":"claude-sonnet-5","max_tokens":128,
"tools":[{"name":"get_weather","description":"Get weather",
"input_schema":{"type":"object","properties":{"city":{"type":"string"}},"required":["city"]}}],
"messages":[{"role":"user","content":"Weather in Tokyo?"}]}'
# 4. Bad key produces a clean 401
curl -s -o /dev/null -w "%{http_code}\n" "$BASE/messages" \
-H "x-api-key: wrong" -H "anthropic-version: 2023-06-01" \
-H "content-type: application/json" -d '{"model":"claude-sonnet-5","max_tokens":8,"messages":[]}'
# 5. Missing version header behaves predictably
curl -s "$BASE/messages" -H "x-api-key: $KEY" \
-H "content-type: application/json" \
-d '{"model":"claude-sonnet-5","max_tokens":8,"messages":[{"role":"user","content":"hi"}]}' | head -c 200
| Step | Pass condition |
|---|---|
| 1 | 200 |
| 2 | Stream ends with message_stop |
| 3 | stop_reason is tool_use and the arguments parse |
| 4 | 401, with a structured error body |
| 5 | A clear error naming the missing version header |
Steps 4 and 5 matter more than they look. A service that turns auth failures into 500, or that returns HTML instead of a structured error, will make every future incident harder to diagnose. You are testing the failure path, which is the one you will actually spend time in.
Frequently asked questions
Does a Claude Pro or Max subscription include API credit?
No. The subscription covers claude.ai. API usage is billed separately from prepaid credit in the Anthropic Console.
Can I recover a key I did not save?
No. Keys are displayed once at creation. Delete the old key and create a new one.
Why does my key work in curl but not in Claude Code?
Almost always a header mismatch. ANTHROPIC_API_KEY sends x-api-key; ANTHROPIC_AUTH_TOKEN sends Authorization: Bearer. Check which is set, and check whether a settings file is overriding your environment variable.
Is there a free tier?
Anthropic's API is prepaid. Some cloud marketplaces and providers offer trial credit, but there is no standing free tier for the direct API.
Which model ID should I use in examples?
Whichever one your Console currently lists. Model IDs change between generations, and an example copied from an article can go stale. Query the model list rather than hardcoding an ID you read somewhere.
Keep reading
Claude Code 中转站怎么选:九项可验证的判断标准
Nine criteria you can test yourself before committing to a gateway (Chinese).
API 密钥安全
Storage, rotation and what to do the moment a key is exposed (Chinese).