> ## Documentation Index
> Fetch the complete documentation index at: https://notes.kodekloud.com/llms.txt
> Use this file to discover all available pages before exploring further.

# How to Generate API Key Securely

> This guide explains how to securely generate and use your OpenAI API key in Python using environment variables.

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.

```bash theme={null}
# macOS/Linux
python3 -m venv venv
source venv/bin/activate

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

<Callout icon="lightbulb" color="#1CB2FE">
  Using a virtual environment is optional but recommended for dependency management.
</Callout>

## 2. Install the OpenAI Python Package

With your environment active, install the official OpenAI library:

```bash theme={null}
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:

| Platform             | Command                                     |
| -------------------- | ------------------------------------------- |
| macOS/Linux          | `export 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 Keys](https://platform.openai.com/account/api-keys) → *Create new secret key*.

<Callout icon="triangle-alert" color="#FF6B6B">
  Never commit your API key—or any secrets—to version control. Consider adding `.env` or environment-specific files to your `.gitignore`.
</Callout>

## 4. Write Your Python Script

Create a file named `example.py`:

```python theme={null}
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:

```bash theme={null}
python example.py
```

Sample output:

```text theme={null}
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.

***

## Links and References

* [OpenAI Quickstart Guide](https://platform.openai.com/docs/quickstart)
* [OpenAI Python Library on PyPI](https://pypi.org/project/openai/)
* [Kubernetes Basics](https://kubernetes.io/docs/concepts/overview/what-is-kubernetes/)

<CardGroup>
  <Card title="Watch Video" icon="video" cta="Learn more" href="https://learn.kodekloud.com/user/courses/introduction-to-openai/module/b6b7bec7-ed21-47d5-afbb-663df59f5e97/lesson/6c8ab32c-658d-4139-ac95-e929de8c6edf" />

  <Card title="Practice Lab" icon="installation" cta="Learn more" href="https://learn.kodekloud.com/user/courses/introduction-to-openai/module/b6b7bec7-ed21-47d5-afbb-663df59f5e97/lesson/f493c45e-434f-48cd-821b-6e4ba818532e" />
</CardGroup>
