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
- Visit Anthropic Console
- Click "Sign Up"
- Register using Email or Google account
- Verify email address
Step 2: Add Account Balance
Important: Anthropic API is a paid service requiring prepaid credits- After login, go to "Billing" page
- Click "Add Credit"
- Select amount (recommended $20-$50 for first time)
- Complete payment with credit card
Step 3: Create API Key
- Go to "API Keys" page
- Click "Create Key"
- Set key name (e.g., claude-code-dev)
- (Optional) Set usage limits and permissions
- Click "Create"
- Important: Copy and save API Key immediately (shown only once!)
API Key Format:
sk-ant-api03-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxConfiguring API Key
There are multiple ways to configure your API Key—choose what works best:
Method 1: Interactive Configuration (Recommended)
# Run configuration command
claude --set-api-key
# Enter API Key
Enter your Anthropic API key: sk-ant-api03-xxxxx
# Confirm save
✓ API key saved successfullyMethod 2: Environment Variable
Temporary (Current Session):
# Linux/macOS
export ANTHROPIC_API_KEY="sk-ant-api03-xxxxx"
# Windows (PowerShell)
$env:ANTHROPIC_API_KEY="sk-ant-api03-xxxxx"Permanent:
Linux/macOS (Bash):
# Edit .bashrc or .zshrc
echo 'export ANTHROPIC_API_KEY="sk-ant-api03-xxxxx"' >> ~/.bashrc
source ~/.bashrcLinux/macOS (Fish):
set -Ux ANTHROPIC_API_KEY "sk-ant-api03-xxxxx"Windows (PowerShell):
[System.Environment]::SetEnvironmentVariable('ANTHROPIC_API_KEY', 'sk-ant-api03-xxxxx', 'User')Method 3: Configuration File
Edit configuration file:
nano ~/.config/claude-code/config.jsonAdd API Key:
{
"api": {
"key": "sk-ant-api03-xxxxx",
"baseUrl": "https://api.anthropic.com"
}
}Method 4: .env File
Create .env file:
3.3 API 定价与使用
# In project or config directory
nano ~/.config/claude-code/.envAdd content:
ANTHROPIC_API_KEY=sk-ant-api03-xxxxxAPI Pricing and Usage
Model Pricing (January 2026)
| Model | Input | Output | Use Case |
|---|---|---|---|
| Claude Opus 4.5 | $15/M tokens | $75/M tokens | Most complex tasks |
| Claude Sonnet 4.5 | $3/M tokens | $15/M tokens | Balanced (Recommended) |
| Claude Haiku | $0.25/M tokens | $1.25/M tokens | Fast 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 安全最佳实践
# View current session usage
claude --usage
# View account balance
claude --balance
# View detailed statistics
claude --statsCost Control Tips
Choose Right Model
- Use Haiku for simple tasks
- Use Sonnet for general tasks
- Use Opus only for complex tasks
Optimize Prompts
- Clear, concise task descriptions
- Reduce unnecessary context
Use Subagents
- Use Explore Agent (haiku) for exploration
- Use Plan Agent for planning
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
# Add to .gitignore
.env
config.json
**/*api-key*2. Use Environment Variables
# 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 管理
# Regularly check for unusual usage
claude --usage-report
# Set budget alerts
claude --set-budget-alert 505. Secure Storage
# 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:
Revoke Key Immediately
- Log into Anthropic Console
- Delete leaked key on API Keys page
Check Usage Records
- Look for abnormal calls
- Check billing
Create New Key
- Generate new API Key
- Update all configurations
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:
cd /path/to/project-a
echo "ANTHROPIC_API_KEY=sk-ant-projectA-xxx" > .envProject B Config:
cd /path/to/project-b
echo "ANTHROPIC_API_KEY=sk-ant-projectB-xxx" > .envClaude Code automatically reads .env from current directory
Scenario 2: Separate Dev and Production Environments
Config File (config.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 验证配置
# Development environment
claude --profile dev "your task"
# Production environment
claude --profile prod "your task"Scenario 3: Individual Keys for Team Members
Team Configuration Recommendations:
- Each member uses their own API Key
- Ignore personal configs in .gitignore
- Provide config template file
# 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 KeyVerify Configuration
After configuration, verify everything works:
# 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!