How do I Use .env Files to Store Secrets Like API Keys?

Learn how to use .env files to store API keys and other secrets securely. Use python-dotenv to load environment variables in your Python projects.

Introduction

Storing sensitive information like API keys directly in your code is not secure. Instead, you should use .env files to store secrets safely. This guide explains how to use dotenv to manage environment variables in Python.


Step 1: Install python-dotenv

  • To use .env files, install the python-dotenv package:
    pip install python-dotenv

Step 2: Create a .env File

  • In your project folder, create a new file named .env.
  • Inside .env, add your secrets:
    API_KEY=your-secret-api-key
    DATABASE_URL=your-database-url

Step 3: Load .env Variables in Python

  • Modify your Python script to load environment variables:
    from dotenv import load_dotenv
    import os
    load_dotenv()
    api_key = os.getenv("API_KEY")
    print(api_key)

Final Thoughts

Using .env files helps keep your credentials safe and prevents accidental exposure. Always add .env to your .gitignore file to avoid committing it to Git.

Next Step: Learn how to uninstall or update Python packages in our next guide: How Do I Uninstall or Update Packages in Python?

Share the Post:

Related Posts