Introduction to OpenAI

Text Generation

How to Generate API Key Securely

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.

# macOS/Linux
python3 -m venv venv
source venv/bin/activate

# Windows (PowerShell)
python -m venv venv
.\venv\Scripts\Activate.ps1

Note

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:

pip install --upgrade openai

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:

PlatformCommand
macOS/Linuxexport OPENAI_API_KEY="your_api_key_here"
Windows (PowerShell)setx OPENAI_API_KEY "your_api_key_here"

If you need an API key, visit:
OpenAI Platform → Settings → API KeysCreate new secret key.

Warning

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:

from openai import OpenAI

# The client automatically reads OPENAI_API_KEY from your environment
client = OpenAI()

prompt = "Tell me a joke"
response = client.chat.completions.create(
    model="gpt-4o-mini",         # select an available model
    messages=[{"role": "user", "content": prompt}],
    max_tokens=150,              # adjust response length
    temperature=0.7,             # controls creativity
)

print(response.choices[0].message.content)

5. Run the Script and Verify the Output

With your environment variable set, execute:

python example.py

Sample output:

Why did the scarecrow win an award?
Because he was outstanding in his field!

Running the script this way ensures your API key remains secure and separate from your codebase.


Watch Video

Watch video content

Practice Lab

Practice lab

Previous
Chat Completions