Skip to main content
  1. Posts/

Managing Secrets and API Keys in Python Projects: .env Guide

··243 words·2 mins·

🔐 Hardcoding API keys in your Python code? That’s a security mistake. Here’s the right solution.

Storing passwords and tokens in source code is dangerous: if it’s uploaded to Git, it’s exposed. 7 practical techniques to do it right:

  1. 📄 Local .env file — store secrets in KEY=value, never in version control. Load with python-dotenv.

  2. 📋 .env.example — a valueless version you DO commit to document what keys are needed.

  3. 🌍 System environment variables — for production: os.environ['API_KEY'] instead of hardcoding.

  4. 🏗️ Separate settings from code — a settings.py module centralizes loading and validation of secrets.

  5. ☁️ Secret managers — AWS Secrets Manager, GCP Secret Manager, Vault for enterprise environments.

  6. Validate at startup — verify all keys are present before the app starts.

  7. 🚫 pre-commit hooks — automatically detect if someone tries to commit a secret.

💡 Explanation in a nutshell
#

A secret in your code is like leaving a house key under the doormat: anyone who sees the code (collaborators, public repositories, logs) can use it. The solution is to store secrets outside the code, in a .env file that’s never uploaded to Git, and load them into your program when needed.

More information at the link 👇

Also published on LinkedIn.
Juan Pedro Bretti Mandarano
Author
Juan Pedro Bretti Mandarano