← Building with AI

API keys and environment variables

Your key is like a password. Keep it out of your code.

Start this lesson

To use a real AI API you need an API key: a long secret string that tells the provider who is paying. Anyone who has your key can spend your money. So never type the key into your code, because code gets shared, copied and uploaded. Instead, store it in an environment variable, a setting that lives on your computer outside the program, and have Python read it with os.environ.

# In your terminal (not in Python), once per session:
#   macOS/Linux:  export ANTHROPIC_API_KEY="your-key-here"
#   Windows:      setx ANTHROPIC_API_KEY "your-key-here"

import os
key = os.environ.get("ANTHROPIC_API_KEY")
if key is None:
    print("Please set the ANTHROPIC_API_KEY environment variable first.")
else:
    print("Key found, it starts with", key[:6])   # never print the whole key

# The Anthropic SDK reads ANTHROPIC_API_KEY by itself:
#   client = anthropic.Anthropic()

os.environ.get returns None if the variable is missing, instead of crashing. That lets you print a friendly message.

In the exercise, the pretend part sets a fake key in os.environ so you can practise reading it. In real life you set it in your terminal, in your computer's settings, or in a hosting service's 'secrets' page, never in the code itself.

Many projects keep keys in a file named .env and load it with a library. If you do that, add .env to your .gitignore file so it never gets uploaded.

If a key ever leaks (for example, you push it to GitHub), go to the provider's console, revoke (delete) it, and make a new one. Deleting the line from your code is not enough, because old versions keep it.