How to authenticate with the Anthropic Claude API. Set API keys securely in Python, Node.js, and shell. Rotate keys, use environment variables, and avoid common mistakes.
The Claude API authenticates every request with an API key passed as a Bearer token. The Anthropic Python and JavaScript SDKs read the key from the environment automatically.
Go to console.anthropic.com → Settings → API Keys → Create Key. Your key starts with sk-ant-.
# In your shell before running:
# export ANTHROPIC_API_KEY="sk-ant-..."
import anthropic
# SDK reads ANTHROPIC_API_KEY automatically
client = anthropic.Anthropic()
# Or pass explicitly (for multi-key setups)
client = anthropic.Anthropic(api_key="sk-ant-...")
msg = client.messages.create(
model="claude-haiku-4-5-20251001",
max_tokens=128,
messages=[{"role": "user", "content": "Hello"}]
)
print(msg.content[0].text)
import Anthropic from "@anthropic-ai/sdk";
// reads process.env.ANTHROPIC_API_KEY automatically
const client = new Anthropic();
const msg = await client.messages.create({
model: "claude-haiku-4-5-20251001",
max_tokens: 128,
messages: [{ role: "user", content: "Hello" }],
});
console.log(msg.content[0].text);
# .env (never commit this file)
ANTHROPIC_API_KEY=sk-ant-...
# Python
from dotenv import load_dotenv
load_dotenv() # loads .env into os.environ
import anthropic
client = anthropic.Anthropic() # reads from env
# Node.js
import "dotenv/config"; // auto-loads .env
import Anthropic from "@anthropic-ai/sdk";
const client = new Anthropic();
# AWS Secrets Manager
import boto3, json, anthropic
secret = boto3.client("secretsmanager").get_secret_value(
SecretId="prod/anthropic-api-key"
)
api_key = json.loads(secret["SecretString"])["ANTHROPIC_API_KEY"]
client = anthropic.Anthropic(api_key=api_key)
# Google Secret Manager
from google.cloud import secretmanager
import anthropic
sm = secretmanager.SecretManagerServiceClient()
name = "projects/MY_PROJECT/secrets/anthropic-api-key/versions/latest"
payload = sm.access_secret_version(name=name).payload.data.decode("utf-8")
client = anthropic.Anthropic(api_key=payload)
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-haiku-4-5-20251001",
"max_tokens": 128,
"messages": [{"role": "user", "content": "Hello"}]
}'
| Practice | Why |
|---|---|
| One key per environment | Revoke prod key without affecting dev |
| Rotate every 90 days | Limit blast radius of a stale leak |
| Add to .gitignore | .env files are the #1 secret-leak vector |
| Enable usage alerts | Catch a leaked key before it costs you |
| Never log the key | Structured logs ship to many downstream sinks |
After authenticating, estimate costs with the Claude API Cost Calculator. For rate limit handling once you're authenticated, see the rate limits guide.