API key and Python SDK setup

Claude API · Essentials · 8 min

Every request needs a key, and keeping it out of your code is the first security habit.

Before Claude will answer, the API needs to know who is calling so it can bill the right account. You prove this with an API key: a long secret string, like a password for programs, that starts with sk-ant-.

To get one, sign in to the Claude Console, open the API keys page and click Create key. The full key is shown only once, so copy it right away. If you lose it, create a new one and delete the old one.

Never paste the key into your source code. Code gets shared, pushed to Git and copied into chat messages. Instead put it in an environment variable, a named setting your operating system passes to every program you start. The SDK looks for one called ANTHROPIC_API_KEY automatically:

export ANTHROPIC_API_KEY="sk-ant-..."

Then create a virtual environment and install the SDK:

python3 -m venv .venv && source .venv/bin/activate
pip install anthropic

The Python SDK needs Python 3.10 or newer. Creating a client is one line, anthropic.Anthropic(), and it reads the key from the environment for you. You can pass api_key=... explicitly, but read the value from os.environ, never from a string literal.

For shared or production systems, prefer a service account key over a personal one, set an expiry date and rotate keys regularly. If a key leaks, revoke it in the Console immediately.

Example

import os
import anthropic

# Fail early with a clear message if the key is missing
if "ANTHROPIC_API_KEY" not in os.environ:
    raise SystemExit("Set ANTHROPIC_API_KEY first")

client = anthropic.Anthropic()          # reads ANTHROPIC_API_KEY
print("SDK version:", anthropic.__version__)

# Same thing, explicit (still from the environment, not a literal):
client = anthropic.Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"])

Remember

  • The key is shown once; store it in ANTHROPIC_API_KEY, not in code
  • pip install anthropic, then anthropic.Anthropic() picks up the key
  • Revoke and replace a key the moment it leaks

Watch out for

  • Committing a .env file or a hard-coded key to Git.

Check yourself

  1. Where should your program get the API key from?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: platform.claude.com/docs/en/get-api-key