Store OpenAI API Key in a .env File (Lesson 15)

What You Will Learn

In this lesson, you will learn:

  • How to store an OpenAI API Key
  • Why you should never hardcode your API key
  • What a .env file is
  • How to create a .env file
  • How to load the API key in Python

By the end of this lesson, your chatbot will work exactly as before, but your API key will be stored safely.


Quick Answer

A .env file is used to store private information such as API keys and passwords. Instead of writing your API key directly in your Python code, you store it in a separate file and load it when your program starts. This is the standard practice used in professional Python projects.


The Problem

Until now, your code looks like this.

client = OpenAI(
    api_key="YOUR_API_KEY"
)

This works, but it has one big problem. If you upload this project to GitHub, everyone can see your API key. Someone could use your API key and consume your API credits. For this reason, you should never hardcode a real API key.


What Is a .env File?

A .env file is a simple text file that stores environment variables. For example:

OPENAI_API_KEY=your_api_key_here

Your Python code reads the value from this file instead of storing it directly in the program.


Step 1: Install python-dotenv

Open the terminal and run:

pip install python-dotenv

If your system uses Python 3, run:

pip3 install python-dotenv

This package allows Python to read values from a .env file.


Step 2: Create a .env File

Inside your AI-Assistant project folder, create a new file named:

.env

Add the following line.

OPENAI_API_KEY=your_api_key_here

Replace your_api_key_here with your actual API key. Do not add quotation marks.


Step 3: Update app.py

At the top of your file, add these imports.

from dotenv import load_dotenv
import os


Step 4: Load the .env File

After the imports, add:

load_dotenv()

This tells Python to load all variables from the .env file.


Step 5: Read the API Key

Replace this code:

client = OpenAI(
    api_key="YOUR_API_KEY"
)

with:

client = OpenAI(
    api_key=os.getenv("OPENAI_API_KEY")
)

Now your program reads the API key from the .env file.


Complete Code

import os

from dotenv import load_dotenv
from openai import OpenAI

load_dotenv()

client = OpenAI(
    api_key=os.getenv("OPENAI_API_KEY")
)

previous_response_id = None

while True:

    user_message = input("You: ")

    if user_message.lower() == "exit":
        print("Goodbye!")
        break

    response = client.responses.create(
        model="gpt-5",
        instructions="""
You are a friendly Python teacher.

Explain every topic in simple English.

Keep your answers short.

Always include an example whenever possible.
""",
        input=user_message,
        previous_response_id=previous_response_id
    )

    print("\nAI:", response.output_text)

    previous_response_id = response.id


How to Check if It Works

Run your chatbot. If everything is correct, it will work exactly as it did before. The only difference is that your API key is no longer stored in the source code.


Common Mistakes

The chatbot says the API key is missing

Check that your .env file is inside the project folder.


Wrong variable name

The variable name should be exactly:

OPENAI_API_KEY

Python treats variable names as case-sensitive.


Forgot to install python-dotenv

Run:

pip install python-dotenv

before running the project.


Best Practice

Never upload your .env file to GitHub. Create a file named .gitignore and add:

.env

This prevents Git from uploading your API key. We’ll learn more about Git in a later module.


Key Points

  • Never hardcode your API key.
  • Store private information in a .env file.
  • Use python-dotenv to load environment variables.
  • Read the API key with os.getenv().

Mini Quiz

1. Where should you store your API key?

A. Inside the Python code

B. Inside a .env file

C. Inside a README file

D. Inside a text comment

Answer: B


2. Which package loads a .env file?

A. requests

B. python-dotenv

C. pandas

D. numpy

Answer: B


3. Which function loads environment variables?

Answer: load_dotenv()


4. Which function reads an environment variable?

Answer: os.getenv()


5. Should you upload your .env file to GitHub?

A. Yes

B. No

Answer: B


Practice Exercise

Complete these tasks.

  1. Install python-dotenv.
  2. Create a .env file.
  3. Move your API key into the .env file.
  4. Update your Python code.
  5. Run the chatbot.

If your chatbot still works, you have successfully secured your API key.


Lesson Summary

Great work! Your chatbot now follows a professional development practice. Instead of storing the API key inside your code, it now reads the key from a .env file. This makes your project safer and easier to share with others.


Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.

Scroll to Top