avatarRichard Taujenis

Summary

The article provides guidance on safely storing API keys in Python projects by using a .env file within a config directory, employing data classes for immutability, and ensuring the .env file is listed in .gitignore.

Abstract

The article titled "How to Safely Store API keys in Python 🔑" outlines best practices for managing API keys in Python projects. It emphasizes the importance of not hardcoding keys directly into scripts, especially when projects become more complex. The recommended approach is to create a config directory containing a config.py file and an .env file to store the actual API keys. The .env file should be included in .gitignore to prevent accidental commits to version control systems like GitHub. The author suggests using the os and dotenv modules to load the environment variables from the .env file and utilizing data classes with the frozen=True attribute to ensure the API keys are immutable within the application. The article also provides a preview of an upcoming YouTube video that will discuss other storage options for API keys.

Opinions

  • The author advocates for a clean project structure, which becomes increasingly important as projects scale and new functionalities are added.
  • It is considered a best practice to store API keys separately from the main code logic, enhancing security and maintainability.
  • The author strongly advises against committing sensitive API keys to GitHub, highlighting the potential risks of exposing them publicly.
  • The use of .env files and data classes in Python is recommended for their effectiveness in managing and protecting API keys within a project.
  • The article suggests that developers should prioritize learning about API key management and secure coding practices as the use of APIs becomes more prevalent in software development.

How to Safely Store API keys in Python 🔑

When I started to be honest I published my API key’s on GitHub as didn't want to bother to add .gitignore to a particular file or write a separate .py script that will handle just that. As you will expand on your projects you will encounter higher usage of different API services.

Where to store them

As I started to create more complex projects I started to separate script’s based on their actions. When it comes to API key’s the case is no different I would suggest to create a config directory and add your config.py and a API file that will store the actual keys.

My project directory tree with API keys in .env file

Clean architecture and project structure is increasing in importance the more you scale and add functionalities.

ALERT: Don’t forget to add config/.env in your .gitignore for unwanted commits/pushes!

Create your constant script

As you probably noticed in the screenshot above I have decided to store my API key’s in .env file. There are other options(which I do not recommend) I will talk about in my YouTube video that will be provided here.

What my .env contains as a example 👇

weatherAPI=apikeyWeather
cryptoAPI=apikeyCrypto
stockAPI=apykeyStock
APIKey=apikeyTwitter
APIKeySecret=apikeyTwitterSecret
BearerToken=apikeyTwitterBearer
AccessToken=apikeyTwitterAccess
AccessTokenSecret=apikeyTwitterAccessSecret

We start by importing the os, dotenv and dataclasses modules.

Use the load_dotenv(find_dotenv()) to find the .env file in local config directory. Data Classes are becoming more of a default for Python and rightfully so.

The frozen=True specifies that the values are immutable.

In the created class will create str variables and using os.getenv(‘Apikey’) we assign the value to it.

//stock.py
from config.config_files import APIkeys
URL = "your_url" + APIkeys.stockAPI

It’s important though to run the script from the main script as otherwise if having similar code architecture structure as I have provided in the first screenshot will resort in ModuleNotFound error.

Concluding

As more and more companies integrate API’s, storing them separate from main code logic and making them immutable should be a priority. Same as not committing to GitHub what never should be there in the first place.

Related Stories

More content at PlainEnglish.io. Sign up for our free weekly newsletter. Follow us on Twitter, LinkedIn, YouTube, and Discord.

Python
API
Oop
Development
Automation
Recommended from ReadMedium