PuppyCoding

Friendly Python & AI tutorials for beginner & intermediate programmers.


How to Hide API Keys in Python

Two mythical beasts protecting a key.

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!



6 responses to “How to Hide API Keys in Python”

  1. […] kept secret, and to do that we can use an “environment variable”. I’ve explained how to hide API keys in Python in another blog post, and so using that method, below is the revised, better code. Note that you […]

    Like

  2. […] is a follow-up to a previous post about how to hide API keys in Python. I received a good question on […]

    Like

  3. […] Here’s a full working example. Note that it uses dotenv (a hidden “.env” file) to hide the OpenAI API keys. […]

    Like

  4. […] recommend you use environment variables to hide your API key instead of putting it directly in your […]

    Like

  5. […] we should use environment variables to hide the API key in a separate file, just in case our program gets shared publicly. This is a good way to do […]

    Like

  6. […] file is automatically hidden (see my tutorial about how to hide API keys) but you can access it from your code with the dotenv and os […]

    Like

Leave a comment