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
import os
from dotenv import load_dotenv, find_dotenv
from dataclasses import dataclass
load_dotenv(find_dotenv())
@dataclass(frozen=True)
class APIkeys:
weatherAPI: str = os.getenv('weatherAPI')
cryptoAPI: str = os.getenv('cryptoAPI')
stockAPI: str = os.getenv('stockAPI')
APIKey: str = os.getenv('APIKey')
APIKeySecret: str = os.getenv('APIKeySecret')
BearerToken: str = os.getenv('BearerToken')
AccessToken: str = os.getenv('AccessToken')
AccessTokenSecret: str = os.getenv('AccessTokenSecret')
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.