Python for AIPython for AI
Tools

Environment & secrets

Keep your API keys safe

When you're building applications, you'll often need to use API keys or other sensitive information. It's super important to handle these "secrets" with care.

Never put secrets in your code

Imagine you're writing a program that uses a service like a weather API. This API probably gives you a special key to identify you. If you put this key directly in your Python code, like this:

python
API_KEY = "sk_your_super_secret_key_12345"

# ... rest of your code using API_KEY

The solution

The best practice is to load secrets from environment variables. These are values set outside your code, often by your operating system or deployment platform. Your code can read them without them being hardcoded.

Python's os module has a function os.getenv() to read environment variables.

python
import os

API_KEY = os.getenv("WEATHER_API_KEY")

if API_KEY is None:
    print("Warning: WEATHER_API_KEY environment variable not set.")
    # Handle the error, maybe exit or use a default

print(f"Using API Key: {API_KEY}")

Before running this code, you'd set the environment variable. Here's how you might do it in the command line (for temporary use in that session):

bash
# On Linux/macOS
export WEATHER_API_KEY="sk_your_super_secret_key_12345"

# On Windows (Command Prompt)
set WEATHER_API_KEY=sk_your_super_secret_key_12345

# On Windows (PowerShell)
$env:WEATHER_API_KEY="sk_your_super_secret_key_12345"