API Key Management Fundamentals
What you'll learn: How to securely handle API keys when working with AI services like OpenAI, Anthropic, and other providers you've been learning about.
What Are API Keys?
API keys are secret strings that authenticate your application to external AI services. Think of them like house keys—they unlock access to paid services and prove you're authorized to use them. When you make requests to OpenAI or Claude's API (concepts you've already learned), the provider checks your API key to verify your identity and track your usage for billing.
A typical API key looks like: sk-proj-abc123xyz789... (OpenAI format).
Where Keys Go Wrong
Never hardcode keys in your source code. This is the #1 security mistake. If you write:
api_key = "sk-proj-abc123..." # ❌ BAD
...and push this to GitHub, your key is now public. Attackers scan repositories specifically for exposed keys.
Proper Key Storage
Use environment variables to keep keys out of code:
import os
api_key = os.environ.get("OPENAI_API_KEY") # ✅ GOOD
Set the environment variable in your terminal before running:
export OPENAI_API_KEY="sk-proj-abc123..."
Or use a .env file (never commit this file to version control—add it to .gitignore).
Basic Security Practices
- Rotate keys regularly through your provider's dashboard
- Use different keys for development vs production
- Set spending limits in provider dashboards to prevent surprise bills
- Never share keys in Slack, email, or public forums
- Revoke immediately if a key is compromised
Key Takeaway: API keys are sensitive credentials—always load them from environment variables, never hardcode them, and treat them like passwords that grant access to paid services.