Lesson 2 / 27
API Keys, Environment Variables and Safe Setup
Create, store and use keys without leaking them.
A key is a password with a credit card attached
An API key identifies and bills your account. Anyone who has it can spend your money and access your data, so treat it like a password. Rules: create separate keys per application and environment; keep keys in environment variables or a secrets manager, never in source code, notebooks, screenshots or chat messages; never ship keys in browser or mobile apps (call the API from your own backend, which authenticates your users); set spend limits and alerts in the provider console; rotate keys on a schedule and immediately if one might have leaked; and add .env to .gitignore. SDKs read standard variables (such as ANTHROPIC_API_KEY and OPENAI_API_KEY) automatically, so you rarely type a key in code.
Reading a key safely (illustrative)
Fail early with a clear message if the variable is missing. Not run here because it needs your real environment.
import os, sys
key = os.environ.get("ANTHROPIC_API_KEY")
if not key:
sys.exit("ANTHROPIC_API_KEY is not set. Export it or load it from your secrets manager.")
# Never print the key. If you must log it for debugging, show only a prefix/suffix:
print("key loaded:", key[:4] + "..." + key[-2:])A leaked key: act within minutes
Revoke it in the console first, create a new one, then check usage logs for abuse. Deleting the commit is not enough because the key may already be copied.
Quick check: Where should an API key live in a web application?
- On your backend, in an environment variable or secrets manager
- In the browser JavaScript
- In a public GitHub repository
- In the page HTML comments
Answer
On your backend, in an environment variable or secrets manager — Anything shipped to a client can be extracted; keep keys server-side.