Module 1 Lesson 4: API Keys and Environment Variables
·LangChain

Module 1 Lesson 4: API Keys and Environment Variables

Security First. How to securely manage your API keys using .env files and prevent accidental leaks.

Securing Your Identity: API Keys

To use models from providers like OpenAI, you need an API Key. This key is your "Identity" and your "Credit Card." If you leak it, anyone can use your budget. As an engineer, the #1 rule is: Never hard-code an API key in your script.

1. Getting Your OpenAI Key

  1. Navigate to platform.openai.com.
  2. Login and go to API Keys.
  3. Create a "Secret Key" and copy it.

2. The .env File Solution

We use a hidden file called .env to store our secrets locally.

Steps:

  1. Create a file named .env in your project root.
  2. Add your key like this:
    OPENAI_API_KEY=sk-abc123yourkeyhere
    

3. Loading Variables in Python

Install the python-dotenv library:

pip install python-dotenv

Then, at the top of your Python script:

import os
from dotenv import load_dotenv

load_dotenv() # This reads the .env file

api_key = os.getenv("OPENAI_API_KEY")

4. Safety: .gitignore

You must never upload your .env file to GitHub. Create a file named .gitignore and add:

.env
venv/
__pycache__/

5. Visualizing the Security Perimeter

graph TD
    S[Python Script] -- Request --> E[.env File]
    E -- Secret --> OS[OS Environment]
    OS -- Provide --> LC[LangChain Model]
    LC -- Authorize --> API[Cloud Provider API]

Key Takeaways

  • API Keys are sensitive secrets; treat them like passwords.
  • Environment Variables allow you to keep secrets separate from code.
  • .env is the standard for local development.
  • .gitignore is mandatory to prevent accidental uploads to the internet.

Subscribe to our newsletter

Get the latest posts delivered right to your inbox.

Subscribe on LinkedIn