How to beginner · 3 min read

How to set Anthropic API key as environment variable

Quick answer
Set your Anthropic API key as an environment variable using export ANTHROPIC_API_KEY='your_api_key' on Unix/macOS or setx ANTHROPIC_API_KEY "your_api_key" on Windows. In Python, access it securely with os.environ["ANTHROPIC_API_KEY"] when initializing the anthropic.Anthropic client.

PREREQUISITES

  • Python 3.8+
  • Anthropic API key
  • pip install anthropic>=0.20

Setup environment variable

To keep your Anthropic API key secure, set it as an environment variable instead of hardcoding it in your code. This method works across operating systems.

  • Unix/macOS: Use the terminal command export ANTHROPIC_API_KEY='your_api_key'.
  • Windows (Command Prompt): Use setx ANTHROPIC_API_KEY "your_api_key" and restart your terminal.

Replace your_api_key with your actual Anthropic API key.

bash
export ANTHROPIC_API_KEY='sk-xxxxxx'

# Windows CMD:
setx ANTHROPIC_API_KEY "sk-xxxxxx"

Step by step usage in Python

After setting the environment variable, use the Anthropic SDK in Python to access it securely and create a client instance.

python
import os
import anthropic

# Initialize client with API key from environment variable
client = anthropic.Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"])

# Example: simple completion request
response = client.messages.create(
    model="claude-3-5-haiku-20241022",
    max_tokens=100,
    system="You are a helpful assistant.",
    messages=[{"role": "user", "content": "Hello Anthropic!"}]
)

print(response.content[0].text)
output
Hello Anthropic! How can I assist you today?

Common variations

You can set environment variables temporarily in your Python script for testing (not recommended for production):

python
import os
os.environ["ANTHROPIC_API_KEY"] = "sk-xxxxxx"  # For testing only

import anthropic
client = anthropic.Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"])

# Use client as usual

Troubleshooting

  • If you get a KeyError for ANTHROPIC_API_KEY, ensure the environment variable is set and your terminal or IDE was restarted after setting it.
  • Verify your API key is correct and has not expired.
  • On Windows, use PowerShell or Command Prompt accordingly and restart the shell after setx.

Key Takeaways

  • Always set your Anthropic API key as an environment variable to keep it secure.
  • Access the API key in Python using os.environ["ANTHROPIC_API_KEY"] when creating the Anthropic client.
  • Restart your terminal or IDE after setting environment variables to ensure they are recognized.
Verified 2026-04 · claude-3-5-haiku-20241022
Verify ↗