Skip to content

OpenAI API Key: Create, Secure, and Use

By the end of this guide you will have an OpenAI API key stored in an environment variable, usage limits configured, and a working Python and cURL call that returns a chat completion. The same approach applies to any runtime that reads environment variables.

Requirement Notes
OpenAI account Sign up at platform.openai.com/signup
Verified email Required before creating keys
Payment method Credit card for pay-as-you-go access
Python 3.9+ or Node.js 18+ To run the verification samples
  1. Sign in at platform.openai.com.
  2. Click your profile icon (top-right) and select API keys, or go to platform.openai.com/api-keys directly.
  3. Click + Create new secret key, give it a name (for example orders-portal-dev), set permissions to All or Restricted as needed, and click Create secret key.
  4. Copy the full key immediately — it starts with sk-proj- and is shown only once. Close the dialog after copying; there is no way to retrieve it again.

Store it in a password manager or secrets vault before you proceed.

API calls are billed per token. A runaway loop or leaked key can generate unexpected charges.

  1. Go to Settings › Billing › Usage limits (or platform.openai.com/account/billing/limits).
  2. Set a Monthly budget so that requests stop when the limit is reached.
  3. Enable email alerts at a lower threshold so you get advance warning before hitting the hard cap.

Linux / macOS (current shell session):

Terminal window
export OPENAI_API_KEY="sk-proj-your-key-here"

Windows PowerShell (current session):

Terminal window
$env:OPENAI_API_KEY = "sk-proj-your-key-here"

.env file for local development (add .env to .gitignore):

OPENAI_API_KEY=sk-proj-your-key-here

Load it in Python with python-dotenv:

from dotenv import load_dotenv
load_dotenv()

For production, use your platform’s secret store: AWS Secrets Manager, Azure Key Vault, GitHub Actions Secrets, or equivalent.

Install the SDK, then run a minimal request to confirm everything is wired correctly.

Terminal window
pip install openai

Save as check_key.py and run with python check_key.py (Python 3.9+):

import openai
import os
client = openai.OpenAI(api_key=os.environ["OPENAI_API_KEY"])
response = client.chat.completions.create(
model="gpt-4o-mini",
max_tokens=16,
messages=[{"role": "user", "content": "Reply with the word VERIFIED."}],
)
print(response.choices[0].message.content)
# Expected output: VERIFIED

Or use cURL directly:

Terminal window
curl https://api.openai.com/v1/chat/completions \
-H "Authorization: Bearer $OPENAI_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "gpt-4o-mini",
"max_tokens": 16,
"messages": [{"role": "user", "content": "Reply with the word VERIFIED."}]
}'

A successful response returns HTTP 200 with choices[0].message.content containing your text.

Model family Typical use
GPT-6, GPT-6.1 (Terra / Sol / Astra) Frontier reasoning, complex multi-step tasks
GPT-4o, GPT-4o mini Balanced general-purpose chat and analysis
o3, o4-mini Deep chain-of-thought reasoning
text-embedding-3-large / text-embedding-3-small Semantic search, RAG
Whisper Audio transcription

Model names and tiers change frequently. Check platform.openai.com/docs/models for the current list before hardcoding a model string.

View keys: The API keys page shows each key’s name, masked value, creation date, and last-used timestamp.

Revoke a key: Click the trash icon and confirm. Any application using that key immediately receives 401 Unauthorized responses.

Rotation policy: Create a replacement key, roll it out to your applications, verify everything works, then delete the old one.

Restricted keys: When creating a key you can limit it to specific endpoints (for example, only Chat completions). Use restricted keys for third-party integrations so a compromised key cannot access billing or fine-tuning endpoints.

Error Likely cause Fix
401 Unauthorized Key missing or revoked Confirm the Authorization: Bearer header is present. Re-check the key value.
429 Too many requests Rate limit exceeded Add exponential backoff. See rate limits guide.
429 Quota exceeded Monthly spending limit reached Increase the limit in Billing settings or wait for the billing cycle to reset.
400 Bad request Missing required field Confirm model, messages, and max_tokens are present in the request body.