How to beginner · 3 min read

How to use OpenAI API with environment variables safely

Quick answer
Use environment variables to store your OpenAI API key securely and access it in Python via os.environ. Initialize the OpenAI client with api_key=os.environ["OPENAI_API_KEY"] to avoid hardcoding sensitive credentials.

PREREQUISITES

  • Python 3.8+
  • OpenAI API key (free tier works)
  • pip install openai>=1.0

Setup environment variables

Store your OpenAI API key in an environment variable to keep it secure and out of your codebase. On Unix-like systems, use export OPENAI_API_KEY='your_api_key'. On Windows PowerShell, use setx OPENAI_API_KEY "your_api_key". Then restart your terminal or IDE to load the variable.

bash
export OPENAI_API_KEY="sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"

Step by step usage in Python

Use the official OpenAI Python SDK v1+ to safely load your API key from environment variables and make a chat completion request.

python
import os
from openai import OpenAI

# Initialize client with API key from environment variable
client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])

# Create a chat completion request
response = client.chat.completions.create(
    model="gpt-4o",
    messages=[{"role": "user", "content": "Hello, how do I use environment variables safely?"}]
)

# Print the assistant's reply
print(response.choices[0].message.content)
output
Hello! To use environment variables safely, store your API key outside your code and access it via os.environ in Python.

Common variations

  • Async usage: Use asyncio with the OpenAI client for asynchronous calls.
  • Different models: Replace model="gpt-4o" with other supported models like gpt-4o-mini.
  • Other SDKs: Anthropic and Google Gemini APIs also support environment variable usage similarly.
python
import os
import asyncio
from openai import OpenAI

async def main():
    client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
    response = await client.chat.completions.acreate(
        model="gpt-4o-mini",
        messages=[{"role": "user", "content": "Async example with env vars."}]
    )
    print(response.choices[0].message.content)

asyncio.run(main())
output
This is an async example showing how to use environment variables safely with OpenAI API.

Troubleshooting

  • KeyError on os.environ: Ensure OPENAI_API_KEY is set in your environment and your terminal/IDE is restarted.
  • Authentication errors: Verify your API key is valid and has not expired or been revoked.
  • Permission denied: Avoid committing your API key to version control; use .gitignore to exclude files containing keys.

Key Takeaways

  • Always store your OpenAI API key in environment variables, never hardcode it.
  • Access environment variables in Python using os.environ for secure API client initialization.
  • Restart your terminal or IDE after setting environment variables to ensure they load properly.
Verified 2026-04 · gpt-4o, gpt-4o-mini
Verify ↗