Module 1 Lesson 4: API Keys and Environment Variables
Security First. How to securely manage your API keys using .env files and prevent accidental leaks.
Securing Your Identity: API Keys
To use models from providers like OpenAI, you need an API Key. This key is your "Identity" and your "Credit Card." If you leak it, anyone can use your budget. As an engineer, the #1 rule is: Never hard-code an API key in your script.
1. Getting Your OpenAI Key
- Navigate to platform.openai.com.
- Login and go to API Keys.
- Create a "Secret Key" and copy it.
2. The .env File Solution
We use a hidden file called .env to store our secrets locally.
Steps:
- Create a file named
.envin your project root. - Add your key like this:
OPENAI_API_KEY=sk-abc123yourkeyhere
3. Loading Variables in Python
Install the python-dotenv library:
pip install python-dotenv
Then, at the top of your Python script:
import os
from dotenv import load_dotenv
load_dotenv() # This reads the .env file
api_key = os.getenv("OPENAI_API_KEY")
4. Safety: .gitignore
You must never upload your .env file to GitHub.
Create a file named .gitignore and add:
.env
venv/
__pycache__/
5. Visualizing the Security Perimeter
graph TD
S[Python Script] -- Request --> E[.env File]
E -- Secret --> OS[OS Environment]
OS -- Provide --> LC[LangChain Model]
LC -- Authorize --> API[Cloud Provider API]
Key Takeaways
- API Keys are sensitive secrets; treat them like passwords.
- Environment Variables allow you to keep secrets separate from code.
.envis the standard for local development..gitignoreis mandatory to prevent accidental uploads to the internet.