How to Keep API Keys Safe: .env Files and Secrets
Keep API keys out of your code: use .env files and environment variables, ignore them in Git, and know exactly what to do if a key leaks.
Short answer: to keep API keys safe, never write them in your code. Put each key in a .env file or an environment variable, add .env to .gitignore so Git never tracks it, and read the key from the environment when the program starts. If a key ever leaks, revoke it in the provider's dashboard and create a new one right away.
Why Do API Keys Need Protection?
An API key works like a password for your account. Anyone who has it can make requests that are billed to you or can read data you can read. Keys leak most often by being pasted into source code that is then pushed to a public repository, or by being shipped inside a web page or mobile app. Automated bots scan public code for keys, so a leaked key can be misused quickly. If you are new to APIs, start with what an API is and how it works.
What Is a .env File?
A .env file is a plain text file of NAME=value lines that lives in your project folder but never in Git. Your program reads the values at start-up, so the secret stays outside the code.
# .env (never commit this file)
MY_API_KEY="paste-your-real-key-here"
MODEL_NAME=some-model-name
Create a second file, .env.example, with the same names but fake values. You commit that one so other people know which variables to set.
How Do You Read the Key in Python?
The popular python-dotenv package loads the file for you. Install it with pip install python-dotenv, then:
import os
from dotenv import load_dotenv
load_dotenv() # copies the lines of .env into environment variables
api_key = os.environ.get("MY_API_KEY")
if api_key is None:
raise SystemExit("Set MY_API_KEY in your .env file first")
Without any package, the same idea works with a few lines of standard Python:
import os
def load_env(path=".env"):
try:
with open(path) as f:
for line in f:
line = line.strip()
if not line or line.startswith("#") or "=" not in line:
continue
name, value = line.split("=", 1)
os.environ.setdefault(name.strip(), value.strip().strip('"'))
except FileNotFoundError:
pass
load_env()
print("MY_API_KEY" in os.environ)
On a real server you usually do not use a file at all. Hosting platforms let you set environment variables or use a secrets manager in their settings. The chapter on environment variables, .env files and virtual environments walks through the full setup.
How Do You Stop Git From Tracking .env?
Add this line to a file named .gitignore in the project root, before your first commit:
.env
Then check that it works with git check-ignore -v .env, which prints the rule that ignores the file. A .gitignore only affects files Git is not yet tracking. If you committed the file earlier, ignoring it later does not remove it from history. The .gitignore chapter explains this in detail.
What Should You Do If a Key Leaks?
Revoke the key first. Delete or rotate it in the provider's dashboard. Deleting it from Git is not enough, because the old value stays in history and in any copies.
Create a new key and update your environment.
Check usage and billing for requests you did not make.
Clean up the code and add the file to
.gitignoreso it does not happen again.
Many code hosting sites also offer secret scanning that warns you when a known key format is pushed. Turn it on if it is available.
Common Mistakes
Putting the key in front-end code. Anything the browser receives can be read by users. Call the API from a backend instead.
Using one key for everything. Make separate keys per project, so you can revoke one without breaking the rest.
Pasting keys into chats, screenshots or notebooks you share. Check before you share.
Forgetting limits. Where possible, set a spending limit and restrict what each key can do.
Key Takeaway
Keep secrets out of your code. Store keys in .env or environment variables, ignore .env in Git, share only a .env.example, and revoke any key that leaks before doing anything else.
Ready to start? You will learn how professional backends handle secrets, authentication and deployment, including what to do when a secret leaks. Begin with the free course Git, APIs and Backend for AI: Advanced.
Related articles
More in APIs and Backend
Frontend vs Backend: What's the Difference?
What the frontend and backend of an app are, how they differ, how they talk to each other and why AI calls and secret keys belong on the backend.
3 min readNov 12, 2026HTTP Status Codes Explained: 200, 404, 500 and More
What HTTP status codes mean, from 200 and 404 to 500, how the five groups work and how your code should react to each.
4 min readNov 9, 2026What Is JSON and Why Do APIs and AI Use It?
JSON is a simple text format for structured data. See what it looks like, its data types, how to read it in Python, and why APIs and AI apps depend on it.
3 min readNov 6, 2026REST API Methods Explained: GET, POST, PUT, PATCH, DELETE
What each REST API method does, with a to-do list example, typical status codes, PUT vs PATCH, and what safe and idempotent mean.
4 min readNov 4, 2026What Are Git and GitHub? The Difference Explained
Git tracks your code's history on your computer; GitHub hosts it online for sharing and teamwork. Learn the difference, the key terms and your first commands.
4 min readNov 2, 2026What Is an API and How Does It Work?
An API explained with a restaurant analogy, then the real parts: endpoints, methods, JSON, status codes and API keys, with a small Python example.
4 min readOct 31, 2026
Comments
Sign in to join the discussion.

