Build with AI

What is an API key, and how do you keep it safe?

· By Robert Scales · 4 min read

Short answer

An API key is a secret code that identifies you to a service such as the OpenAI API, so every request made with it is billed to your account. Keep it out of your code: store it in an environment variable on the machine that runs your program, never put it in web pages or apps that users download, and never commit it to a code repository.

When you sign up for the OpenAI API, or almost any other web service that developers use, you receive an API key. It looks like a long string of random letters and numbers. Behind the scenes, it works like a password and a credit card number combined: it tells the service who is calling, and it decides whose account pays for each request.

That is why a key needs the same care as a bank card. OpenAI's help center describes the key as a unique code that identifies your requests and is meant for you alone. Anyone who copies it can send requests as you, use up your quota and leave you with the bill.

What an API key does

API stands for application programming interface: a way for one program to ask another program to do something. When your script asks GPT-3 to write a summary, it sends a request over the internet to OpenAI's servers. The key travels with that request. The server checks it, finds your account, applies your usage limits and records the tokens you used.

Three practical consequences follow:

  • The key is personal. Each person on a team should have their own key. OpenAI's terms do not allow sharing keys; you invite teammates to your account instead, and each gets a key of their own.
  • The key has value. A stolen key can run up charges, drain your monthly quota and get your access interrupted.
  • The key must stay on the server side. Whatever computer sends the request has to hold the key, so that computer must be one you control.

Where keys leak

Most leaks come from two places.

Front-end code. Code that runs in a visitor's web browser, or in an app people install on their phone, is delivered to their device. Anyone can open the browser's developer tools or unpack the app and read what is inside, including a key pasted into it. If a web page needs GPT-3, the page should send the user's text to your own small server, and that server, holding the key, calls OpenAI and passes back the answer.

Code repositories. Developers store code in version control systems such as Git, and often share it on sites like GitHub. OpenAI's help center lists committing a key to source code as a common way keys get compromised. In a public repository, the key is visible to the whole internet. Even a private repository is only as safe as every account and service with access to it.

The fix for both is the same principle. The Twelve-Factor App, a widely cited guide to building web software, says configuration such as credentials should be kept strictly apart from code. It offers a simple test: could you publish your code as open source right now without exposing a single secret? If the answer is no, a secret is in the wrong place.

A worked example: using an environment variable

An environment variable is a named value stored by your computer's operating system rather than inside your program. Your code asks for the value by name when it runs. OpenAI recommends the name OPENAI_API_KEY, which also means teammates can share the same code while each uses their own key.

Step 1: store the key (macOS or Linux with the zsh shell). Replace the placeholder with your key:

echo "export OPENAI_API_KEY='paste-your-key-here'" >> ~/.zshrc
source ~/.zshrc

On older Macs and many Linux systems using bash, use ~/.bash_profile instead of ~/.zshrc. On Windows, the command setx OPENAI_API_KEY "paste-your-key-here" does the same job; open a new command window afterward.

Step 2: read it in your program. In Python:

import os
import openai

openai.api_key = os.environ["OPENAI_API_KEY"]

response = openai.Completion.create(
    engine="text-davinci-001",
    prompt="Write a one-sentence welcome message for a library newsletter.",
    max_tokens=40,
)
print(response.choices[0].text.strip())

The key appears nowhere in the file. You can commit this script, share it or post it in a forum without risk.

Step 3: keep local secret files out of Git. Some projects store variables in a file called .env instead. If you do, add .env to your .gitignore file so Git never tracks it. The Twelve-Factor guide notes the weakness of this approach: such files are easy to commit by mistake, which is why environment variables set outside the project are the safer default.

For applications in production, OpenAI also suggests a key management service, a dedicated product that stores secrets encrypted and separate from your application, so a breach of the app does not expose the key.

Try it: Search a project of yours for the start of your API key, including old files and notebooks. If you find it anywhere, move it into an environment variable, change the code to read os.environ, and run the script to confirm it still works.

What should you do if a key leaks?

Act quickly, because anyone who finds a published key can start using it right away. First, rotate the key: in your OpenAI account, go to the API Keys page, create a new key and revoke the old one, so the leaked copy stops working. Then update every program and server that used the old key.

Next, look at the Usage page and check whether recent activity matches your own work. Unexpected spikes are a sign that someone else used the key. If you see misuse, contact OpenAI support so they can investigate.

Finally, close the hole that caused the leak. Deleting the key from your latest code is not enough if it was committed to Git, because the old version stays in the repository's history. Revoking the key is what protects you; cleaning the history and moving the secret into an environment variable keeps it from happening again.

Sources

  1. Best Practices for API Key Safety — OpenAI Help Center
  2. The Twelve-Factor App: III. Config — Adam Wiggins (12factor.net)

Get the free Guide to Artificial Intelligence

Sign up for the weekly newsletter and receive the free guide: what changed in AI this week, one lesson, one prompt to try. Unsubscribe in one click.

How we handle your address

Back to top

Display

Your choices are saved in this browser only. No data is sent.

Text size
100%
Colours
Reading
More settings
Accessibility statement