← All posts
·10 min read

Claude Code API Keys: Setup in 4 Steps

Claude CodeAPI KeysSetupConfiguration
Claude Code API Keys: Setup Guide

How Claude Code authentication works

Claude Code needs to authenticate with Anthropic's API to function. Unlike IDE extensions that handle auth through a GUI, Claude Code runs in your terminal and uses environment variables or interactive login to connect. If you are setting up Claude Code from scratch, start with our complete setup guide.

There are two authentication paths:

  1. API key (BYOK) - You provide your own Anthropic API key. Pay per token. Full control over spending.
  2. Subscription login - You authenticate with a Claude Pro or Max subscription. Fixed monthly cost. Usage limits apply. See our Claude Code pricing breakdown to compare the two paths by cost.

Which path you choose depends on how much you use Claude Code and how much control you need over billing. Both work with the same features - the difference is purely about cost structure and rate limits.

Getting your Anthropic API key

Step 1: Create an Anthropic account

Go to console.anthropic.com and create an account. You can use email, Google, or GitHub authentication. If your organization already has an Anthropic account, ask your admin to add you to the existing workspace.

Step 2: Navigate to API keys

Once logged in, click API Keys in the left sidebar. This takes you to the key management page where you can create, view, and revoke keys.

Step 3: Generate a new key

Click Create Key. You will be asked to:

  • Name the key - Use something descriptive like "claude-code-laptop" or "ci-pipeline-staging". You will have multiple keys eventually, and clear names prevent confusion.
  • Set permissions - For Claude Code usage, you need standard API access. No special permissions required.

The key is displayed once. Copy it immediately and store it securely. You cannot view the full key again after this screen.

Step 4: Add billing

API keys require a payment method and credits. Go to Settings > Billing in the Anthropic console to add a credit card and purchase credits. You can set spending limits to prevent unexpected charges.

Starting credit recommendations:

Usage level Monthly budget What that covers
Light (learning) $5-10 Several hundred requests, enough for exploration
Regular (daily use) $20-50 Full workday usage with moderate complexity tasks
Heavy (power user) $50-100+ Extended sessions, subagents, large codebases
Team/CI $100-500+ Multiple developers plus automated pipelines

You can set hard spending limits in the Anthropic console so you never exceed your budget accidentally.

Configuring your API key

Environment variable (recommended)

The standard approach is setting the ANTHROPIC_API_KEY environment variable. Claude Code checks for this automatically on startup.

For zsh (default on macOS):

# Add to ~/.zshrc
export ANTHROPIC_API_KEY="sk-ant-api03-your-key-here"

Then reload your shell:

source ~/.zshrc

For bash:

# Add to ~/.bashrc
export ANTHROPIC_API_KEY="sk-ant-api03-your-key-here"

For fish:

# Add to ~/.config/fish/config.fish
set -x ANTHROPIC_API_KEY "sk-ant-api03-your-key-here"

Per-project configuration with .env

For projects where you want to use a different API key (or a different team's billing), create a .env file in the project root:

ANTHROPIC_API_KEY=sk-ant-api03-project-specific-key

Make sure .env is in your .gitignore. Never commit API keys to version control.

Claude Code reads .env files automatically when you start a session in that directory. Project-level keys override the global environment variable.

Interactive login (subscription users)

If you use Claude Pro or Max instead of API keys, authenticate through the interactive flow:

claude
# On first run, Claude Code opens a browser for authentication
# Log in with your Anthropic account
# Authorization completes automatically

This stores a session token locally. You do not need to manage API keys at all with this method.

Pro vs API vs Max: choosing the right plan

This is where most people get confused. Here is the straightforward breakdown:

Claude Pro ($20/month)

  • What you get: Access to Claude Code with usage limits
  • Rate limits: Approximately 45 messages per 5-hour window (varies by model and message complexity)
  • Best for: Developers who use Claude Code a few times per day for specific tasks
  • Limitation: You will hit rate limits during heavy sessions. When the limit hits, you wait.

For a deeper look at rate limits and how to handle them, see our rate limit fix guide.

Claude Max ($100/month or $200/month)

  • What you get: Significantly higher rate limits on Claude Code
  • Rate limits: 5x (at $100) or 20x (at $200) the Pro limits
  • Best for: Developers who use Claude Code as their primary coding tool throughout the day
  • Limitation: Still has limits, just much higher. The $200 tier is effectively unlimited for most workflows.

See our Max plan deep dive for a detailed breakdown of whether it is worth the upgrade.

API (BYOK - Bring Your Own Key)

  • What you get: Pay-per-token access with no rate limits (within your tier)
  • Cost: ~$3 per million input tokens, ~$15 per million output tokens (Claude Sonnet 4). Opus costs more.
  • Best for: Teams, CI/CD pipelines, heavy usage where you want precise cost control
  • Limitation: No spending cap by default - you must set limits manually in the console

Which should you pick?

Your situation Best plan
Trying Claude Code for the first time Pro ($20/month)
Using it daily but hitting Pro limits Max $100/month
Using it all day, every day Max $200/month or API
Running in CI/CD pipelines API (headless mode requires it)
Team of 3+ developers API with organization billing
Need to track costs per project API (token-level billing)

You can switch between plans at any time. Many developers start with Pro, upgrade to Max when they hit limits, and eventually move to API when they need team-level control.

Managing multiple API keys

As your usage grows, you will likely need multiple keys for different purposes:

Separate keys for separate concerns

# Personal development
export ANTHROPIC_API_KEY="sk-ant-api03-personal-dev"

# CI pipeline (set in CI environment)
ANTHROPIC_API_KEY="sk-ant-api03-ci-pipeline"

# Staging environment
ANTHROPIC_API_KEY="sk-ant-api03-staging"

Key rotation

Rotate API keys periodically as a security practice:

  1. Generate a new key in the Anthropic console
  2. Update your environment variable or .env file
  3. Verify Claude Code works with the new key
  4. Revoke the old key in the console

Do not skip step 3. Revoking the old key before confirming the new one works will lock you out until you fix it.

Team key management

For teams, use Anthropic's workspace feature:

  • Workspace billing - All team members' usage bills to a single account
  • Per-user keys - Each developer generates their own key within the workspace
  • Usage tracking - Monitor per-user consumption in the Anthropic console
  • Spending limits - Set per-key or per-workspace limits

This is far better than sharing a single API key across the team. Shared keys create security risks and make it impossible to track who used what.

Environment variables beyond API keys

Claude Code respects several environment variables that control its behavior. Understanding these helps you configure sessions precisely:

Core variables

Variable Purpose Example
ANTHROPIC_API_KEY API authentication sk-ant-api03-...
CLAUDE_CODE_MODEL Override the default model claude-sonnet-4-20250514
CLAUDE_CODE_MAX_TOKENS Maximum output tokens per response 16384
CLAUDE_CODE_USE_BEDROCK Use AWS Bedrock instead of direct API 1
CLAUDE_CODE_USE_VERTEX Use Google Vertex AI instead of direct API 1

Cloud provider authentication

If your organization uses Claude through AWS Bedrock or Google Vertex instead of the direct Anthropic API, you need different environment variables:

AWS Bedrock:

export CLAUDE_CODE_USE_BEDROCK=1
export AWS_REGION="us-east-1"
export AWS_ACCESS_KEY_ID="your-access-key"
export AWS_SECRET_ACCESS_KEY="your-secret-key"

Google Vertex:

export CLAUDE_CODE_USE_VERTEX=1
export CLOUD_ML_REGION="us-east5"
export ANTHROPIC_VERTEX_PROJECT_ID="your-project-id"

These routes are common in enterprises that already have cloud provider agreements. The Claude Code experience is identical - only the billing and network path changes.

For a complete guide to environment variables, see our environment variables deep dive.

Security best practices

Never commit API keys

This should be obvious, but it happens constantly. Protect yourself:

# .gitignore
.env
.env.local
.env.*.local

If you accidentally commit a key, revoke it immediately in the Anthropic console and generate a new one. Do not just remove it from the code and push again - the key is already in git history.

Use a secrets manager for teams

For team deployments, store API keys in a proper secrets manager rather than individual .env files:

  • 1Password CLI - op read "op://Development/Anthropic/api-key"
  • AWS Secrets Manager - Integrate with your existing AWS infrastructure
  • HashiCorp Vault - Enterprise-grade secret management
  • Doppler - Developer-focused secrets platform

Load the key at session start rather than persisting it in a file:

# In .zshrc
export ANTHROPIC_API_KEY=$(op read "op://Development/Anthropic/api-key")

Monitor for leaked keys

Anthropic will notify you if your API key appears in a public repository. But don't rely on that alone:

  • Enable GitHub's secret scanning on your repositories
  • Use pre-commit hooks to catch keys before they are committed
  • Set up billing alerts so unexpected usage triggers a notification

Set spending limits

Always set a spending limit in the Anthropic console, even if you think you won't hit it. Runaway scripts, forgotten CI jobs, or misconfigured automation can burn through credits fast. To cut the bill at the source rather than just capping it, Claude Code cost optimization covers the model routing and context habits that drive token spend.

Go to Settings > Billing > Spending Limits in the console and set a monthly maximum that makes sense for your usage.

Troubleshooting common API key issues

"Invalid API key" error

  • Verify the key starts with sk-ant-api03-
  • Check for trailing whitespace or newline characters in your environment variable
  • Ensure the key hasn't been revoked in the console
  • Confirm you are using the key from the correct workspace

"Insufficient credits" error

  • Check your balance at console.anthropic.com
  • Add credits or update your payment method
  • Verify your spending limit hasn't been reached

"Rate limited" with API key

API keys have rate limits based on your usage tier. New accounts start at Tier 1 with lower limits. As you spend more, you automatically upgrade to higher tiers with increased limits:

Tier Requirement Requests per minute
Tier 1 New account 50
Tier 2 $40+ spent 1,000
Tier 3 $200+ spent 2,000
Tier 4 $400+ spent 4,000

If you need higher limits immediately, contact Anthropic support with your use case.

Key works in curl but not Claude Code

This usually means the environment variable isn't being loaded in the shell where Claude Code runs:

# Verify the variable is set
echo $ANTHROPIC_API_KEY

# If empty, check which shell config file is being loaded
echo $SHELL
# Then ensure the export is in the correct file (.zshrc, .bashrc, etc.)

Frequently asked questions

Can I use one API key for both Claude Code and the Claude API directly?

Yes. The same Anthropic API key works for Claude Code, the REST API, Python SDK, TypeScript SDK, and any other tool that connects to Anthropic's API. Usage from all sources bills against the same account balance. If you want to separate billing by use case, create different keys - they all draw from the same workspace credits, but you can track usage per key in the console.

What happens if my API key is leaked or compromised?

Revoke it immediately in the Anthropic console under API Keys. Click the delete button next to the compromised key. Then generate a new key and update your environment variables. Any usage from the leaked key between the leak and revocation will be billed to your account. Anthropic monitors for public key exposure and may proactively disable keys found in public repositories.

Is the Pro subscription or API key better value for Claude Code?

It depends on volume. Pro at $20/month is cheaper if you make fewer than roughly 300-400 requests per month (the equivalent API cost). Above that, API billing can exceed $20 quickly, especially with complex prompts on large codebases. Max at $100/month is better value than API for most individual heavy users. API billing only wins on value when you need precise cost tracking, CI/CD integration, or team-level management. Start with Pro, track your usage, and upgrade when the limits feel restrictive.

Get Claudify - Pre-configured Claude Code setup with API key management built in. One command: npx create-claudify.

More like this

Ready to upgrade your Claude Code setup?

Get Claudify
Featured on Dofollow.Tools AI Toolz Dir