Every request needs a key, and keeping it out of your code is the first security habit.
The API needs to know who is calling so it can bill the right account. Your program proves this with an API key: a secret string, like a password for programs.
Create one in the dashboard at platform.openai.com under API keys. Keys belong to a project, a folder inside your organisation with its own keys, limits and usage reports. Using one project per app makes costs easy to see and a leaked key easy to cut off. Copy the key when it is shown; you will not see it again.
Never write the key in your code. Put it in an environment variable, a named setting your operating system hands to the programs you start. The SDK reads OPENAI_API_KEY automatically:
export OPENAI_API_KEY="sk-..."(On Windows PowerShell use setx OPENAI_API_KEY "sk-..." and open a new terminal.)
Then install the SDK in a virtual environment:
python3 -m venv .venv && source .venv/bin/activate
pip install openaiOpenAI() creates a client that picks up the key. There is also AsyncOpenAI() for async programs; it has the same methods. If a key ever lands in Git, a chat or a screenshot, revoke it in the dashboard and create a new one.
Example
import os
import openai
from openai import OpenAI
if "OPENAI_API_KEY" not in os.environ:
raise SystemExit("Set OPENAI_API_KEY first")
client = OpenAI() # reads OPENAI_API_KEY
print("SDK version:", openai.__version__)
# Explicit form, still read from the environment:
client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])Remember
- Keys belong to projects; one project per app keeps things tidy
- Store the key in OPENAI_API_KEY;
OpenAI()reads it pip install openai; revoke leaked keys immediately
Watch out for
- Committing a key to Git, where bots find it within minutes.