Whether you’re using the ChatGPT API or any other API that requires keys for authentication, here’s how to easily keep those keys secret by using environment variables.
The concept is simple: Store your keys in your Python environment, not in your Python code.
Note: Use the alternate method for hiding API keys if you’re deploying code to a server.
1. Create a Hidden File
First, in your terminal, create a hidden file with the name .env
using the nano
command (or your preferred text editor).
Now put your API keys in this file using a KEYNAME=value
format, like this:
OPENAI_API_KEY=sk-your-api-key-goes-here
2. Access the API Key in Python
Next, in your Python program, use the following code to access the key:
import os
from dotenv import load_dotenv
load_dotenv()
openai.api_key = os.getenv("OPENAI_API_KEY")
This code imports the necessary Python modules (os
and dotenv
), loads the hidden file (.env
), and replaces the hard-coded API key with a hidden one. Even if you put your files on GitHub, for example, your hidden .env
file is not shared.
With this method, your API key is now hidden and safe! Use the same steps to secure other API keys. Happy safe coding!
Leave a comment