Claude API: authentication error

  • Python
  • Claude API

You may see

anthropic.AuthenticationError: Error code: 401
invalid x-api-key

Stay safe: Keep API keys secret. If one leaks, delete it in the console.

Why it happens

  • The key isn't set in this terminal.
  • It was copied with a space, or has been deleted.

How to fix it

  1. Set the key in an environment variable, as the Anthropic docs show, and open a new terminal.
  2. Make a new key in the Anthropic console if needed.
  3. Never paste the key into the program.

It worked if: A short test message gets a reply.

From the official documentation. From Anthropic's API errors page. Sources: Anthropic: API errors.

Didn't help? Search another error or ask us.