Skip to main content
Managing sensitive credentials like your OpenAI API key with environment variables helps you avoid hard-coding secrets in your source code. In this guide, you’ll learn how to:
  • Create an isolated Python environment
  • Install required packages
  • Store your API key safely
  • Write and run a simple Python script using the OpenAI client

1. (Optional) Create and Activate a Virtual Environment

Isolating dependencies prevents conflicts across projects.
Using a virtual environment is optional but recommended for dependency management.

2. Install the OpenAI Python Package

With your environment active, install the official OpenAI library:

3. Configure Your API Key as an Environment Variable

Storing credentials in environment variables keeps them out of your codebase. Use the command for your OS: If you need an API key, visit:
OpenAI Platform → Settings → API KeysCreate new secret key.
Never commit your API key—or any secrets—to version control. Consider adding .env or environment-specific files to your .gitignore.

4. Write Your Python Script

Create a file named example.py:

5. Run the Script and Verify the Output

With your environment variable set, execute:
Sample output:
Running the script this way ensures your API key remains secure and separate from your codebase.

Watch Video

Practice Lab