How To Use a .env File With Python

How To Use a .env File With Python

We've all been there before, pushing login credentials or API tokens to GitHub. This can cause many issues, like getting your account that's linked to the API you're using suspended. All because of bots finding your API token on GitHub. Perhaps someone finds your connection string to your online hosted database and removes all your data.

GIF

Preventing these situations is easy with two files:

  • a .env file
  • a .gitignore file

In this blog post, we will go over how to set these two files up and how to use them in your Python 3 project. Let's go!

Pre-requirements

It helps to know about a couple of things to understand this blog post better:

  • How to set up a Python project
  • How basic Python syntax works
  • How to use pip
  • How to use git (git init, git status)

For example 2 it also helps to know how public APIs work with Python.

What Are These Files

we need to know what these files are and do first. You never want to code with something you don't understand.

What Is a .env File

An Environment Variables file is a text file you can use by naming it '.env' in your project folder. It's a simple way to save global variables that you want to use but don't want out there on the internet. Examples of these are:

  • Database credentials
  • Login credentials
  • API tokens
  • Private keys
  • Crypto Wallet keys

What Is a .gitignore File

The name already says it all. A .gitignore file is a text file that tells git to ignore files from being committed. You don't want to commit your .env file because all your secret credentials are in there. That's why you want a .gitignore file to exclude it.

GIF

The Practical Coding Examples

There are two practical examples in this blogpost you can either read through or recreate if you want to. The first one is a very simple one where we hide your favorite language in the .env file. The second example includes the use of an API key. It helps to understand how APIs and dictionaries work, but it's not a must.

Before We Get Started

If we want to use a .env file, there's one thing we need to install first. We need the 'python-dotenv' package with pip to get the .env file to actually work.

To install python-dotenv, use this command in the terminal:

pip install python-dotenv

Don't forget to re-build or re-open your Python project before trying to use the package.

Example One: This Is My Favorite Language

In this example, we want to print your favorite language. The discussion about what the best language is can be controversial on the internet. This is why we're going to keep it a secret from GitHub. Python is my favorite language, so that's what I'm going to use.

To get started we need two files in the project folder:

  • main.py (you can also give it another name as long as it's a Python file)
  • .env

Okay, now the fun part! We're going to code.

1. Add a variable

To create a variable that contains the string 'Python' we can add the following to the .env file:

LANGUAGE = Python

The variable name in a .env file should always be uppercase.

2. Use the variable in the Python file

Using this variable in the Python file is easier than you might think!

First, we need some packages to get Python to work together with the .env file. These are: dotenv and os.

We import them like this:

from dotenv.main import load_dotenv
import os

Next up you need to tell python-dotenv to load in our variables and os to search for the variables. We can do that by adding these two lines:

load_dotenv()
favorite_language = os.environ['LANGUAGE']

3. Look at the result

That's it! Now we can use a print statement to tell the world what your favorite language is

The print function to let people know:

print("My favorite programming language is: " + favorite_language) 
# Prints My favorite programming language is: Python

GIF Here's all the code we should have in the Python file after this example:

from dotenv.main import load_dotenv
import os

load_dotenv()

favorite_language = os.environ['LANGUAGE']

print("My favorite programming language is: " + favorite_language)

Example Two: The Simple Superhero API

We will add another variable to the .env file for this second example. This time, we're going to hide an API key because that's something you should want to keep secret at all times.

This article isn't about how API calls work. Because of this, I won't be going into huge detail about what the code does. If you are interested in learning how to use an API with Python, take a look at this blogpost on Rapid API

We all love Batman (right?), so the plan is to create a small terminal application that shows:

  • His name ('Batman')
  • His actual name ('Bruce Wayne')

This info comes from a public API called 'Superhero API '. GIF

1. Add variable to the .env file

We need to add the API key to the .env file. We do this so we can keep it secret from git later on. We call this variable API_KEY:

API_KEY=3928193820281931

This API key example is fake. You will have to generate your own on the website if you want to try it yourself.

2. Add the imports we need to the Python file

We need the imports we already used and some new ones for API requests and JSON converting. Here's what we need in code at the top of our Python file:

from dotenv.main import load_dotenv
from urllib.request import Request, urlopen
import os, json

load_dotenv()

3. Fetch the API data and convert it from JSON

The next step is that we're going to send a GET request to the API. After doing that, convert the JSON data we received to a dictionary. We can use that dictionary for the console application later on.

Here is the call reference we're going to use:

https://superheroapi.com/api/api-key/character-id/biography

To make life a little easier, I figured out that the ID for batman is 70.

To request the API data, get the data and turn it into a dictionary, we add the following code to the Python file:

api_key = os.environ['API_KEY']

url = "http://www.superheroapi.com/api.php/" + api_key +"/70/biography" # Url to API

api_request = Request(url, headers={'User-Agent': 'Mozilla/5.0'}) # The header needs to be added due to the APIs security

data = urlopen(api_request).read() # Calls the API request and reads the JSON data it receives.

data_to_dict= json.loads(data)

4. Get the data from the dictionary

We need to get the data (superhero- & real name) from the dictionary to a string variable. This is possible by using a dictionary.get('a key value from the dictionary').

name = data_to_dict.get('name')
real_name = data_to_dict.get('full-name')

5. Look at your result

And there we have it! All we have to do now is print those values to the terminal. GIF

print("Superhero name: " + name + ", Real name: " + real_name)
# Result will be Superhero name: Batman, Real name: Bruce Wayne

Once we've done all of this the Python file will look something like this:

from dotenv.main import load_dotenv
import os, json
from urllib.request import Request, urlopen

load_dotenv()

api_key = os.environ['API_KEY']
url = "http://www.superheroapi.com/api.php/" + api_key +"/70/biography"
api_request = Request(url, headers={'User-Agent': 'Mozilla/5.0'})

data = urlopen(api_request).read()
data_to_dict= json.loads(data)

name = data_to_dict.get('name')
real_name = data_to_dict.get('full-name')

print("Superhero name: " + name + ", Real name: " + real_name)

Adding The .gitignore File

The first thing we need to do is to set up a local repository. We can do this by opening the terminal in your project folder and running git init. If you've never used git before, or the git command isn't recognized, you probably need to install it first.

Next, we run git status in the terminal. With this command, git will show you what files it can commit for you. image.png

We don't want to commit the .env file. That would lead to our secret variables being public. That's why we're going to create a .gitignore file.

The simplest and quickest way to set up a .gitignore file is to write down .env on the first line and save it.

What I prefer more is going to gitignore.io and searching for 'Python.' It will give you a page with plain text with all kinds of files and folders to ignore that are common for Python (including .env). Copy and paste the raw text to the .gitignore file you made in your project folder.

The text we get from gitignore.io if we search for 'Python' looks like this: image.png

If we copy the text, it will look something like this in the text editor: image.png

Now you've got yourself a working .gitignore file. Don't forget to save it!

Finishing up

That's all! All there's left to do now is commit and push your code to your GitHub repository. If you run git status you can tell Git can't commit the .env file anymore. It's not on the list. image.png

GIF

The End

Thank you so much for reading. I hope this blog post helped you. Don't be afraid to reach out on Twitter or Instagram for any questions or remarks. You can also comment on this post. See you later!