Skip to main content
Lesson 3 of 22 · Responses API: OpenAI Fundamentals

Authentication, API Keys, and Organization

Lesson 3 of 22 Updated July 29, 2026 Developer
On this page
  1. Authentication, API Keys, and Organization
  2. Create Your Account and Get a Key
  3. Which Key Type to Choose
  4. Organizations and Projects
  5. Never Expose Your Keys
  6. Verify Your Configuration
  7. Key Takeaways

Authentication, API Keys, and Organization

Before you write a single line of code, you must configure your API access. This lesson covers creating keys, structuring access through organizations and projects, and the security precautions that prevent the classic nightmare: accidentally pushing a key to a public repository where a stranger consumes it overnight.

Create Your Account and Get a Key

The process takes three steps. First, go to platform.openai.com and create an account; you will automatically receive free credits to start experimenting. Next, navigate to the API Keys section of the dashboard and generate a new key. You will see this key only once: copy it immediately, but do not paste it into your code.

# Your API key looks like this (never share it!)
# sk-proj-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

# Best practice: use an environment variable
import os
api_key = os.environ.get("OPENAI_API_KEY")

The third step is declaring the environment variable, which depends on your platform. On a development machine, a .env file loaded by python-dotenv is often the most convenient. On a server, prefer an environment variable defined by your orchestrator or secrets service.

# Linux / macOS — add to ~/.bashrc or ~/.zshrc
export OPENAI_API_KEY="sk-proj-your-key-here"

# Windows PowerShell
$env:OPENAI_API_KEY = "sk-proj-your-key-here"

# .env file (with python-dotenv)
# .env
OPENAI_API_KEY=sk-proj-your-key-here

Which Key Type to Choose

Project keys, identifiable by their sk-proj- prefix, are tied to a specific project and offer the best control. You will use these in almost every case. The SDK detects them automatically once the environment variable is set, which is why OpenAI() instantiates without arguments in all examples in this course.

from openai import OpenAI

# The SDK automatically detects OPENAI_API_KEY
client = OpenAI()

# Or specify explicitly (not recommended for production)
client = OpenAI(api_key="sk-proj-...")

Service keys are the second type. Designed for server applications requiring elevated access, they grant additional permissions and therefore demand extra care: store them in a secrets vault and never distribute their value to a development workstation.

Organizations and Projects

Access is structured across three nested levels:

  1. Organization: Your company or team
  2. Project: A logical grouping (e.g., “Production Chatbot”, “Data Analysis”)
  3. API Key: Linked to a specific project

If you belong to multiple organizations, specify the one you intend to use when instantiating the client:

from openai import OpenAI

# Specify the organization (useful if you belong to multiple)
client = OpenAI(
    organization="org-xxxxxxxxxxxx",
    project="proj-xxxxxxxxxxxx"
)

Take the time to split your usage into projects rather than routing everything through a single key. You will see the benefit at the first sign of trouble. Each project has its own usage tracking, allowing you to attribute costs to a specific feature rather than an opaque monthly total. Rate limits are also separated: a nightly batch job that saturates its quota will not prevent your chatbot from responding to customers. You can then assign different members to each project, and crucially, revoke a compromised key without interrupting other applications.

Never Expose Your Keys

The rule is simple and absolute: a key never appears in source code. The contrast between the two snippets below speaks louder than a long lecture.

# BAD — hardcoded key in code
client = OpenAI(api_key="sk-proj-abc123")  # DANGER!

# GOOD — environment variable
client = OpenAI()  # Automatically reads OPENAI_API_KEY

# GOOD — .env file with python-dotenv
from dotenv import load_dotenv
load_dotenv()
client = OpenAI()

The corollary concerns your .gitignore, which must exclude local configuration files before your first commit, not after. A key that is published and then deleted remains present in the repository history.

# ALWAYS add these lines to your .gitignore
.env
.env.local
.env.production
*.key

Finally, plan for regular rotation, every 90 days. You can do this without downtime: create a new key, update your deployments, and then delete the old one only once nothing is using it anymore.

Verify Your Configuration

Before moving on, run this script. It checks for the presence of the key, displays a truncated version to confirm it is the correct one, and then makes a real call. Rerun this test whenever an environment behaves strangely.

from openai import OpenAI
import os

def verify_configuration():
    """Verify that the API configuration is correct."""
    
    # Check for the key
    api_key = os.environ.get("OPENAI_API_KEY")
    if not api_key:
        print("ERROR: OPENAI_API_KEY not defined")
        return False
    
    print(f"Key detected: {api_key[:8]}...{api_key[-4:]}")
    
    # Test the connection
    try:
        client = OpenAI()
        response = client.responses.create(
            model="gpt-5.6-terra",
            input="Reply only: OK"
        )
        print(f"Connection successful: {response.output_text}")
        return True
    except Exception as e:
        print(f"Connection ERROR: {e}")
        return False

verify_configuration()
# Expected result:
# Key detected: sk-proj-...xxxx
# Connection successful: OK

Key Takeaways

  • Use project keys (sk-proj-...) for each application
  • Store your keys in environment variables, never in code
  • Organize your access with the Organization → Project → Key hierarchy
  • Perform regular rotation of your keys (every 90 days)
  • Always add .env to your .gitignore