Lesson 2 of 8 · Basics
API Keys and Keeping Them Secret
Keep AI API keys safe: environment variables, .env files and secret managers, never in browser or app code, spending limits, one key per project, and leaks.
- 6 min read
- Beginner
- Reviewed
- Why a leaked AI API key is costly
- Where keys belong: environment variables, .env files and secret managers
- Why keys must never be in browser or mobile app code
- Damage limits: spending caps, separate keys and rotation
A key is a credit card
AI keys are a popular target. Automated tools scan public code repositories, shared notebooks and websites for anything that looks like a key, and can start using one within minutes of it appearing. A leaked key can run up a large bill, use up your rate limits, and get your account suspended for abuse you didn't commit.
Where keys belong
Environment variables. Your program reads the key from the environment at run time, so it never appears in the code.
import os
def load_api_key(name):
key = os.environ.get(name) # read the key from an environment variable
if not key:
print(f"No key found. Set the {name} environment variable first.")
return None
return key
def mask(key):
# Safe to print or log: only the first 3 and last 4 characters
return key[:3] + "..." + key[-4:]
# In this browser example nothing is set, so we fake it for the demonstration.
# On your own computer you would set it in your terminal or a .env file instead.
os.environ["EXAMPLE_AI_KEY"] = "sk-demo-1234567890abcdefWXYZ"
key = load_api_key("EXAMPLE_AI_KEY")
if key:
print("Loaded key:", mask(key))
load_api_key("SOME_OTHER_KEY")The SDKs of the major providers read a standard environment variable automatically, such as OPENAI_API_KEY or ANTHROPIC_API_KEY, so often you don't pass the key in your code at all.
A .env file for local development. A small text file next to your project:
ANTHROPIC_API_KEY=your-key-goes-hereA library such as python-dotenv loads it into the environment when your program starts. Add .env to your .gitignore file before your first commit, so it is never uploaded.
A secret manager in production. Hosting platforms and cloud providers have a settings page or service for secrets. The platform injects them as environment variables when your app runs, and controls who on the team can see them.
Never in the browser or a mobile app
The safe pattern is a backend: the user's browser talks to your server, and your server, which holds the key, talks to the AI provider. Your server can also check who the user is, limit how much each user can do, and filter requests.
Browser or app --> your server (holds the key) --> AI providerLimit the damage
Assume that one day a key will leak, and make that day boring:
- Set spending limits and alerts in the provider's dashboard.
- Use separate keys per project and per environment (development, production). If one leaks, you revoke only that one, and usage reports show which project is spending.
- Give each key the least access it needs, where the provider supports scopes or restricted keys.
- Rotate keys regularly: create a new one, switch your app over, then delete the old one.
- Mask keys in logs: show only the first few and last few characters.
Common mistakes
Logs are often shared and stored. Mask the key so it can be recognised but not used.
key = "sk-proj-9f8e7d6c5b4a3210QRST" # Print a masked version for the logs: the first 7 characters, then "...", # then the last 4 characters. Expected: sk-proj...QRST
You are building a web page that answers questions with an AI model. Where should the API key live?
Summary
- An AI API key is like a credit card: a leak costs money and can get your account suspended.
- Keep keys in environment variables, a .env file (git-ignored) locally, and a secret manager in production.
- Never put keys in browser or mobile app code; call the AI from your own server.
- Set spending limits, use separate keys, rotate them and mask them in logs.
- If a key leaks: revoke it first, then replace, check usage and fix the cause.
Next: making your first real API call.
Finished reading? Tick it off to track your progress.