API Keys - Using Environment Variables in Python Projects
Secure your Python applications with environment variables
Hard coding API keys directly in your Python scripts creates a significant security vulnerability. If your code is pushed to GitHub or shared publicly, your API key becomes exposed to anyone who views the repository.
Common Security Vulnerabilities
Exposed API Keys
API keys hard-coded in source files can be discovered by malicious actors. This leads to unauthorized usage and potential billing issues.
Version Control Exposure
Pushing sensitive data to GitHub or other repositories makes it permanently accessible in commit history. Even deleting it later doesn't remove the historical record.
Password Storage
Database passwords and other credentials stored in plain text within code files create multiple attack vectors for data breaches.
Setting Up Environment Variables
Create .env File
Create a new file named .env at the root level of your project, alongside your server files. This file has no name, only the .env extension.
Add Variables
Paste your API key variable into the .env file without quotes or spaces around the value. Use the format VARIABLE_NAME=value.
Install dotenv
Install the Python-dotenv package using pip install Python-dotenv to enable loading environment variables in your Python application.
Load Variables
Import load_dotenv and call it in your Python script, then use os.getenv to access your environment variables securely.
Before vs After: API Key Storage
| Feature | Insecure Method | Secure Method |
|---|---|---|
| Storage Location | Directly in Python file | Separate .env file |
| Version Control Risk | High - exposed in commits | Low - .env excluded |
| Code Readability | API key visible to all | Clean, no sensitive data |
| Security Level | Vulnerable | Protected |
Before installing new packages, use 'pip show package-name' to check if a module is already installed. This helps avoid unnecessary installations and potential conflicts.
Environment variables exist as key-value pairs, which is why OPENAI_API_KEY is in quotes when using os.getenv - we're referencing a key, not a regular variable name.
Environment Variable Implementation Checklist
Ensures the file is accessible to your main application files
Prevents parsing errors when loading the variable
Required dependency for loading .env files in Python
Enables access to environment variable loading functionality
Actually loads the variables from .env into the environment
Retrieves environment variables by their key names
Allows easy rollback if environment setup doesn't work
Ensures the API still works with the new environment variable setup
Environment Variables vs Hard-Coded Values
This lesson is a preview from our Python for AI Course Online (includes software) and Python Certification Course Online (includes software & exam). Enroll in a course for detailed lessons, live instructor support, and project-based training.
Key Takeaways