Fix Claude API Error 401 -- Authentication Failed

TL;DR: A 401 error means your API key is missing, invalid, or expired. Verify your key, check environment variables, and ensure the correct header format.

The Problem

When calling the Claude API, you receive an HTTP 401 response:

{
  "type": "error",
  "error": {
    "type": "authentication_error",
    "message": "Invalid API key"
  }
}

Why This Happens

The Anthropic API requires a valid API key in the x-api-key header. A 401 occurs when:

The Fix

Step 1: Verify Your API Key

# Check if the environment variable is set
echo "Key length: ${#ANTHROPIC_API_KEY}"
echo "Key prefix: ${ANTHROPIC_API_KEY:0:10}..."
# Key should start with "sk-ant-" and be ~100+ characters

Step 2: Set the API Key Correctly

macOS / Linux (bash/zsh):

export ANTHROPIC_API_KEY="sk-ant-api03-your-key-here"
source ~/.zshrc

In code (Python SDK):

import anthropic
# SDK reads ANTHROPIC_API_KEY automatically
client = anthropic.Anthropic()

Step 3: Verify the Header Format

If making raw HTTP requests, use x-api-key (not Authorization):

# Correct
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-4-5-20250514","max_tokens":128,"messages":[{"role":"user","content":"Hi"}]}'

Common Variations

ScenarioCauseQuick Fix
401 in CI/CD pipelineSecret not injectedCheck CI secret configuration
401 after key rotationOld key cachedRestart application, clear env cache
401 with SDKANTHROPIC_API_KEY not exportedAdd export before the variable
401 with trailing newlineCopy-paste artifactUse echo -n when setting key

Prevention

Paste your error into our Error Diagnostic for an instant fix.

Master Claude Code

Get lifetime access to all ClaudHQ tools, advanced workflows, and production-grade templates.

Get Lifetime Access

Written by the ClaudHQ team ยท Expert Claude Code guides and tools