Skip to content

Chapter 3: API Configuration

Getting Anthropic API Key

The Anthropic API Key is essential for using Claude Code. Let's walk through obtaining one:

Step 1: Register Anthropic Account

  1. Visit Anthropic Console
  2. Click "Sign Up"
  3. Register using Email or Google account
  4. Verify email address

Step 2: Add Account Balance

Important: Anthropic API is a paid service requiring prepaid credits
  1. After login, go to "Billing" page
  2. Click "Add Credit"
  3. Select amount (recommended $20-$50 for first time)
  4. Complete payment with credit card

Step 3: Create API Key

  1. Go to "API Keys" page
  2. Click "Create Key"
  3. Set key name (e.g., claude-code-dev)
  4. (Optional) Set usage limits and permissions
  5. Click "Create"
  6. Important: Copy and save API Key immediately (shown only once!)

API Key Format:

sk-ant-api03-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

Configuring API Key

There are multiple ways to configure your API Key—choose what works best:

bash
# Run configuration command
claude --set-api-key

# Enter API Key
Enter your Anthropic API key: sk-ant-api03-xxxxx

# Confirm save
 API key saved successfully

Method 2: Environment Variable

Temporary (Current Session):

bash
# Linux/macOS
export ANTHROPIC_API_KEY="sk-ant-api03-xxxxx"

# Windows (PowerShell)
$env:ANTHROPIC_API_KEY="sk-ant-api03-xxxxx"

Permanent:

Linux/macOS (Bash):

bash
# Edit .bashrc or .zshrc
echo 'export ANTHROPIC_API_KEY="sk-ant-api03-xxxxx"' >> ~/.bashrc
source ~/.bashrc

Linux/macOS (Fish):

bash
set -Ux ANTHROPIC_API_KEY "sk-ant-api03-xxxxx"

Windows (PowerShell):

powershell
[System.Environment]::SetEnvironmentVariable('ANTHROPIC_API_KEY', 'sk-ant-api03-xxxxx', 'User')

Method 3: Configuration File

Edit configuration file:

bash
nano ~/.config/claude-code/config.json

Add API Key:

json
{
  "api": {
    "key": "sk-ant-api03-xxxxx",
    "baseUrl": "https://api.anthropic.com"
  }
}

Method 4: .env File

Create .env file:

3.3 API 定价与使用

bash
# In project or config directory
nano ~/.config/claude-code/.env

Add content:

env
ANTHROPIC_API_KEY=sk-ant-api03-xxxxx

API Pricing and Usage

Model Pricing (January 2026)

ModelInputOutputUse Case
Claude Opus 4.5$15/M tokens$75/M tokensMost complex tasks
Claude Sonnet 4.5$3/M tokens$15/M tokensBalanced (Recommended)
Claude Haiku$0.25/M tokens$1.25/M tokensFast simple tasks

M = Million

Cost Estimation Examples

Simple Task (Fix small bug):

  • Input: ~1,000 tokens
  • Output: ~500 tokens
  • Cost: ~$0.01 (Sonnet 4.5)

Medium Task (Implement new feature):

  • Input: ~5,000 tokens
  • Output: ~2,000 tokens
  • Cost: ~$0.05 (Sonnet 4.5)

Complex Task (Refactor large module):

  • Input: ~20,000 tokens
  • Output: ~8,000 tokens
  • Cost: ~$0.20 (Sonnet 4.5)

View Usage

3.4 API 安全最佳实践

bash
# View current session usage
claude --usage

# View account balance
claude --balance

# View detailed statistics
claude --stats

Cost Control Tips

  1. Choose Right Model

    • Use Haiku for simple tasks
    • Use Sonnet for general tasks
    • Use Opus only for complex tasks
  2. Optimize Prompts

    • Clear, concise task descriptions
    • Reduce unnecessary context
  3. Use Subagents

    • Use Explore Agent (haiku) for exploration
    • Use Plan Agent for planning
  4. Set Budget Limits

    json
    {
      "limits": {
        "dailyBudget": 10,
        "monthlyBudget": 100,
        "warningThreshold": 80
      }
    }

API Security Best Practices

🔒 Protect Your API Key

1. Never Commit to Version Control

bash
# Add to .gitignore
.env
config.json
**/*api-key*

2. Use Environment Variables

bash
# Recommended: use environment variables, not hardcoded
export ANTHROPIC_API_KEY="sk-ant-xxx"

3. Limit Key Permissions

  • Set key permissions in Anthropic Console
  • Create separate keys for different environments
  • Rotate API Keys regularly

4. Monitor Usage

3.5 多 API Key 管理

bash
# Regularly check for unusual usage
claude --usage-report

# Set budget alerts
claude --set-budget-alert 50

5. Secure Storage

bash
# Limit config file permissions
chmod 600 ~/.config/claude-code/config.json

# Encrypt sensitive config (optional)
gpg -c ~/.config/claude-code/config.json

⚠️ Response to Leakage

If API Key is leaked:

  1. Revoke Key Immediately

    • Log into Anthropic Console
    • Delete leaked key on API Keys page
  2. Check Usage Records

    • Look for abnormal calls
    • Check billing
  3. Create New Key

    • Generate new API Key
    • Update all configurations
  4. Update Security Measures

    • Check .gitignore
    • Strengthen access control

Managing Multiple API Keys

For teams or multi-project scenarios, you might need to manage multiple API Keys:

Scenario 1: Different Projects with Different Keys

Project A Config:

bash
cd /path/to/project-a
echo "ANTHROPIC_API_KEY=sk-ant-projectA-xxx" > .env

Project B Config:

bash
cd /path/to/project-b
echo "ANTHROPIC_API_KEY=sk-ant-projectB-xxx" > .env

Claude Code automatically reads .env from current directory

Scenario 2: Separate Dev and Production Environments

Config File (config.json):

json
{
  "profiles": {
    "dev": {
      "api": {
        "key": "sk-ant-dev-xxx",
        "model": "claude-haiku"
      }
    },
    "prod": {
      "api": {
        "key": "sk-ant-prod-xxx",
        "model": "claude-sonnet-4-5"
      }
    }
  }
}

Use Different Profiles:

3.6 验证配置

bash
# Development environment
claude --profile dev "your task"

# Production environment
claude --profile prod "your task"

Scenario 3: Individual Keys for Team Members

Team Configuration Recommendations:

  1. Each member uses their own API Key
  2. Ignore personal configs in .gitignore
  3. Provide config template file
bash
# config.template.json
{
  "api": {
    "key": "YOUR_API_KEY_HERE",
    "baseUrl": "https://api.anthropic.com"
  }
}

# Members copy template and fill in their key
cp config.template.json config.json
# Edit config.json with personal API Key

Verify Configuration

After configuration, verify everything works:

bash
# 1. Test API connection
claude --test-connection

# Expected output
 API key valid
 Connection to api.anthropic.com successful
 Model claude-sonnet-4-5 available
 Account balance: $45.23

# 2. View current configuration
claude --show-config

# 3. Test simple task
claude "echo 'Configuration test successful'"

# 4. Check which API Key is loaded
claude --which-api-key

# Output: Using API key: sk-ant-***xxx (last 4 chars shown)

Summary

In this chapter, we learned:

  • ✅ How to register Anthropic account and obtain API Key
  • ✅ Four methods to configure API Key
  • ✅ API pricing and cost estimation
  • ✅ API security best practices
  • ✅ Multiple API Key management strategies
  • ✅ Configuration verification methods

Important Reminders:

  • 🔐 Safeguard your API Key
  • 💰 Monitor costs, set budget alerts
  • 🔄 Rotate API Keys regularly
  • 📊 Monitor usage

Next Step: In Chapter 4, we'll start actually using Claude Code and complete your first task!


Content is for learning and research only.