How to hide API keys from git in Python (hide credentials from git)

Arturo Sbr
2 min readAug 26, 2022

This article will show you how to hide your credentials from git by saving them as environment variables and loading them in Python using dotenv.

What’s wrong with hardcoding your credentials?

Hardcoding your credentials is a terrible idea, especially if you are using some kind of version control tool (like git). Anyone with access to the project would be able to see your passwords, and that’s not good.

How to hide your credentials

As it turns out, it is possible to use git without compromising your credentials. I broke the process down into three steps.

I’ll be using terminal for the remainder of this article. However, in case you’re not comfortable using shell, feel free to manually create blank files and fill them in using TextEdit, Notepad or some other text editor.

Step 1

The first thing you should do is tell git not to track .env files. To do this, open a new Terminal, set the working directory at your project’s folder and add .env files to the list of ignored files with the following commands (you can ignore the first line in case you already have a .gitignore file):

% touch .gitignore
% echo ".env" > .gitignore

Step 2

Next, create a .env file and and declare your keys in it with the format variable_name=value. That is:

% touch .env
% echo "MY_PASSWORD=Your Password Here"
% echo "MY_API_KEY=Scary Terry Will Never find this here"

Important: Note that there’s no spaces on either side of the = signs!

Step 3

Given that the .env file is hidden from git, we can now safely call our credentials in Python:

# Important libraries
import os
from dotenv import load_dotenv
# Load secret .env file
load_dotenv()
# Store credentials
pwd = os.getenv('MY_PASSWORD')
key = os.getenv('MY_API_KEY')
# Verify it worked
if pwd is not None and key is not None:
print('It worked')

Important: Note that the arguments passed to os.getenv() are the same as what you named them in your .env file.

Closing remarks

That’s it! You can now safely include your credentials in your code without git tracking them!

--

--