Module 2: OpenAI API - Introduction

OpenAI Account Setup and API Keys

Capsule overview

Before writing code, you need:

  1. An OpenAI account
  2. An API key (authentication token)
  3. A configured payment method (or the $5 free credits)

This capsule guides you step by step through the complete setup. By the end, you'll have your API key ready to use in Python.

Time: 15 minutes
Cost: $0 (use the initial $5 free credits)


🎯 Objectives

By completing this capsule:

  • ✅ You'll have an active OpenAI account
  • ✅ You'll get your first API key
  • ✅ You'll configure environment variables (.env)
  • ✅ You'll verify that everything works

📝 Step 1: Create an OpenAI Account

1.1 Sign up:

  1. Visit: https://platform.openai.com/signup
  2. Sign-up options:
    • Email + password
    • Google account
    • Microsoft account

Recommendation: Use Google/Microsoft (fewer steps)


1.2 Email verification:

If you signed up with email:

  1. Check your inbox (check spam too)
  2. Click the verification link
  3. Confirm the account

1.3 Profile configuration:

OpenAI will ask you for:

  • Full name
  • Organization (optional, you can put "Personal")
  • Country (for tax compliance)
  • Intended use (select "Learning/Education")

Note: This info is for compliance, it doesn't affect functionality.


💳 Step 2: Configure Billing

2.1 Free credits ($5):

New users (2024-2026):

  • OpenAI gives $5 in free credits
  • Valid for 3 months
  • Enough for this entire module

Check your credits:

  1. Go to: https://platform.openai.com/account/billing/overview
  2. Look for "Free trial credits"
  3. You should see: $5.00 available

2.2 If you do NOT have free credits:

Existing users or expired credits:

You need to add a payment method:

  1. Go to: https://platform.openai.com/account/billing/payment-methods
  2. Click "Add payment method"
  3. Options:
    • Credit/debit card
    • PayPal (some countries)

⚠️ Important: Configure a spending limit

  1. Go to: https://platform.openai.com/account/billing/limits
  2. Set "Hard limit": $10/month (recommended for learning)
  3. Set "Soft limit": $5/month (early alert)

What this does:

  • Hard limit: OpenAI stops requests if you reach $10
  • Soft limit: It sends you an alert email at $5
  • Prevents: An unexpected $500 bill from a bug

2.3 Verify billing is active:

Dashboard → Billing → Overview

You should see:

Current balance: $5.00 (free credits)
OR
Current balance: $0.00 (paid, with a card configured)

If it says "Please add payment method": Complete step 2.2


🔑 Step 3: Create an API Key

3.1 Generate an API key:

  1. Go to: https://platform.openai.com/api-keys
  2. Click "Create new secret key"
  3. Give it a descriptive name:
    • Example: "Module 2 - Learning"
    • Example: "Local Development"
  4. Click "Create secret key"

3.2 Copy and save:

⚠️ CRITICAL: You'll only see the key ONCE

sk-proj-abc123def456ghi789jkl012mno345pqr678stu901vwx234yz

Copy it NOW to a safe place:

  • A local temporary file (not the cloud)
  • A password manager (1Password, Bitwarden)
  • A note on your machine

If you lose it: You must regenerate it (the previous one becomes invalid)


3.3 Verify the format:

OpenAI API keys have this format:

sk-proj-XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
  • Starts with sk-proj- (project key, new 2024 format)
  • Or sk- (user key, old format)
  • ~50-60 characters
  • Only letters, numbers, hyphens

If your key does NOT look like this: Something went wrong, regenerate it.


🔐 Step 4: Configure Environment Variables

4.1 Why environment variables?

❌ BAD (hardcoded):

import openai
openai.api_key = "sk-proj-abc123..."  # NEVER DO THIS

Problems:

  • If you commit to Git → Public leak
  • If you share the code → You expose your key
  • Bots scraping GitHub steal keys in minutes

✅ GOOD (environment variable):

import os
openai.api_key = os.getenv("OPENAI_API_KEY")

Benefits:

  • The key is NOT in the code
  • .gitignore prevents commits
  • Different keys per environment (dev/prod)

4.2 Create a .env file:

In your project, create a .env file:

cd ~/your-project
touch .env

Contents of .env:

OPENAI_API_KEY=sk-proj-abc123def456ghi789jkl012mno345pqr678stu901vwx234yz

Replace sk-proj-abc123... with YOUR real key.


4.3 Configure .gitignore:

⚠️ CRITICAL: Prevent a leak

Create/edit .gitignore:

# In the project root
nano .gitignore

Add these lines:

# Environment variables
.env
.env.local
.env.*.local

# OpenAI specific
openai.key
api_key.txt
secrets/

Verify it works:

git status
# .env should NOT appear in "Untracked files"

4.4 Install python-dotenv:

To read .env from Python:

pip install python-dotenv

Usage in code:

from dotenv import load_dotenv
import os

# Load variables from .env
load_dotenv()

# Access the key
api_key = os.getenv("OPENAI_API_KEY")
print(f"API Key loaded: {api_key[:10]}...")  # Show the first 10 chars

Expected output:

API Key loaded: sk-proj-ab...

✅ Step 5: Complete Verification

5.1 Test with curl:

Verify that your API key works WITHOUT writing Python:

curl https://api.openai.com/v1/models \
  -H "Authorization: Bearer $OPENAI_API_KEY"

Expected output (first lines):

{
  "object": "list",
  "data": [
    {
      "id": "gpt-4-turbo",
      "object": "model",
      ...
    },
    {
      "id": "gpt-3.5-turbo",
      "object": "model",
      ...
    }
  ]
}

If you see this: ✅ The API key works

If you see a 401 Unauthorized error:

{
  "error": {
    "message": "Invalid API key",
    "type": "invalid_request_error"
  }
}

❌ Wrong key, verify:

  1. You copied it in full (no spaces)
  2. It's in .env correctly
  3. You used export OPENAI_API_KEY=... in the terminal

5.2 Test with Python (minimal):

Create test_api_key.py:

from dotenv import load_dotenv
import os
import requests

# Load .env
load_dotenv()
api_key = os.getenv("OPENAI_API_KEY")

# Verify key exists
if not api_key:
    print("❌ ERROR: OPENAI_API_KEY not found in .env")
    exit(1)

print(f"✅ API Key loaded: {api_key[:15]}...")

# Test API call (list models)
headers = {"Authorization": f"Bearer {api_key}"}
response = requests.get("https://api.openai.com/v1/models", headers=headers)

if response.status_code == 200:
    models = response.json()["data"]
    print(f"✅ API works! {len(models)} models available")
    print(f"Examples: {models[0]['id']}, {models[1]['id']}")
else:
    print(f"❌ ERROR: {response.status_code} - {response.text}")

Run it:

python test_api_key.py

Expected output:

✅ API Key loaded: sk-proj-abc123...
✅ API works! 50 models available
Examples: gpt-4-turbo, gpt-3.5-turbo

🔒 Security Best Practices

1. NEVER commit API keys:

Check before committing:

git diff | grep -i "sk-"
# If "sk-proj" or "sk-" appears → STOP

If you already committed one by mistake:

  1. Regenerate the key IMMEDIATELY in the dashboard
  2. Revoke the old key
  3. Update .env with the new key
  4. Git: git filter-branch or BFG Repo Cleaner (advanced)

2. Use project-specific keys:

Instead of 1 key for everything:

Project A: sk-proj-AAA...
Project B: sk-proj-BBB...
Learning:  sk-proj-LLL...

Benefit: If one leaks, the others are safe.


3. Regular rotation:

Every 3-6 months:

  1. Generate a new key
  2. Update .env in all projects
  3. Revoke the old key

Automatable with:

  • 1Password rotation
  • AWS Secrets Manager
  • HashiCorp Vault (enterprise)

4. Usage monitoring:

Dashboard → Usage:

Alert if:

  • Usage > $1/day (when you expect $0.10)
  • An unexpected spike (possible leak)

🐛 Troubleshooting

Error: "Invalid API key"

Symptoms:

401 Unauthorized: Invalid API key

Solutions:

  1. Verify the format (must start with sk-proj- or sk-)
  2. Check for spaces (copy without leading/trailing spaces)
  3. Regenerate the key in the dashboard
  4. Verify that .env is in the correct directory

Error: "You exceeded your current quota"

Symptoms:

429 Too Many Requests: You exceeded your current quota

Causes:

  1. You spent the $5 free credits
  2. You don't have a payment method configured
  3. You reached the hard limit

Solution:

  1. Dashboard → Billing → Add payment method
  2. Or wait for it to reset (if it's a temporary rate limit)

Error: ".env doesn't load"

Symptoms:

api_key = None  # should be "sk-proj..."

Causes:

  1. .env is NOT in the project root
  2. You didn't run load_dotenv()
  3. A typo in the variable (case-sensitive)

Solution:

# Verify the location
pwd  # Must be the project root
ls -la .env  # Must exist

# Verify the contents
cat .env
# Must have: OPENAI_API_KEY=sk-proj-...

📊 Summary

Completion checklist:

  • OpenAI account created and verified
  • $5 credits visible OR a payment method configured
  • Spending limits configured ($5 soft, $10 hard)
  • API key generated and saved
  • .env file created with the key
  • .gitignore configured (prevents a leak)
  • python-dotenv installed
  • curl test successful
  • Python test successful

If all are ✅: Ready to write code!


🔗 Additional resources

  1. OpenAI Platform Quickstart - Official setup
  2. API Keys Best Practices - Security
  3. Billing FAQ - Common questions
  4. python-dotenv docs - Environment variables

➡️ Next step

Next capsule: 03-your-first-request-with-the-python-sdk.md

Now that you have a working API key, you'll make your first request to GPT-3.5:

  • You'll install the OpenAI SDK
  • You'll send a simple message
  • You'll receive a response
  • You'll understand the request/response format

Time: 20 minutes
Code: ~10 lines


Estimated time: 15 minutes
Next: 03-your-first-request-with-the-python-sdk.md