API Keys
An API key is a unique identifier that authenticates your application with the AI API. It is like a password that tells the API server who is making the request and what account to bill.
What is an API Key?
An API key is a long string of characters that uniquely identifies your account.
Example format (OpenAI):
`sk-proj-...` (about 50 characters)
Every request you make to the API must include your API key. The server checks your key to:
1. Confirm you are an authorized user
2. Track how many tokens you have used
3. Bill your account for usage
4. Apply your account's rate limits and permissions
Deep Learning ⊂ Machine Learning ⊂ Artificial Intelligence
CRITICAL: API Key Security
# SECURE: How to use an API key safely
import os
# NEVER do this:
# api_key = "sk-proj-your-actual-key-here" # WRONG - hardcoding keys is dangerous
# ALWAYS do this instead:
# Read the key from an environment variable
api_key = os.environ.get("OPENAI_API_KEY")
if not api_key:
raise ValueError(
"OPENAI_API_KEY environment variable is not set. "
"Set it before running this script."
)
print("API key loaded securely from environment variable.")
print(f"Key starts with: {api_key[:7]}..." if api_key else "No key found")
# How to set the environment variable:
# Windows (Command Prompt): set OPENAI_API_KEY=sk-proj-your-key
# Windows (PowerShell): $env:OPENAI_API_KEY="sk-proj-your-key"
# Mac/Linux (Terminal): export OPENAI_API_KEY=sk-proj-your-key
# For projects: use a .env file (add it to .gitignore!)
# OPENAI_API_KEY=sk-proj-your-key
# Then load with: pip install python-dotenv
# from dotenv import load_dotenv; load_dotenv()CRITICAL Security Warning
Warning
NEVER hardcode an API key directly in your source code. NEVER commit an API key to Git or GitHub. NEVER share an API key in a public forum or screenshot. A leaked API key can be used by anyone to make requests on your account, which can result in unexpected charges (sometimes thousands of dollars). If your key is ever exposed, immediately revoke it in the API provider's dashboard and create a new one.