How to set OpenAI API key as environment variable
Quick answer
Set your OpenAI API key as an environment variable using your OS shell (e.g.,
export OPENAI_API_KEY='your_key' on Unix or setx OPENAI_API_KEY "your_key" on Windows). In Python, access it securely with os.environ["OPENAI_API_KEY"] to authenticate API requests.PREREQUISITES
Python 3.8+OpenAI API key (free tier works)pip install openai>=1.0
Setup environment variable
Set your OpenAI API key as an environment variable to keep it secure and avoid hardcoding it in your code. Use your operating system's shell to define OPENAI_API_KEY.
- On macOS/Linux (bash/zsh):
export OPENAI_API_KEY='your_api_key_here' - On Windows Command Prompt:
setx OPENAI_API_KEY "your_api_key_here" - Restart your terminal or IDE after setting the variable to apply changes.
Step by step usage in Python
Use the os module to read the environment variable and the official OpenAI SDK v1+ to make a request.
import os
from openai import OpenAI
# Initialize client with API key from environment variable
client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
# Make a simple chat completion request
response = client.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": "Hello, OpenAI!"}]
)
print(response.choices[0].message.content) output
Hello, OpenAI!
Common variations
You can set environment variables temporarily in your shell session or permanently in your shell profile file (e.g., ~/.bashrc, ~/.zshrc). For Windows PowerShell, use $Env:OPENAI_API_KEY = "your_api_key_here" for the session.
Use different models by changing the model parameter, e.g., gpt-4o-mini or gpt-4o.
Troubleshooting
- If you get a
KeyErrorforOPENAI_API_KEY, ensure the environment variable is set and your terminal/IDE was restarted. - If authentication fails, verify your API key is correct and has not expired or been revoked.
- Use
print(os.environ.get("OPENAI_API_KEY"))in Python to debug if the key is accessible.
Key Takeaways
- Always set your OpenAI API key as an environment variable to keep it secure.
- Access the API key in Python using
os.environ["OPENAI_API_KEY"]for authentication. - Restart your terminal or IDE after setting environment variables to ensure they are loaded.