C.W.K.
Stream
Lesson 05 of 08 · published

Authentication

~22 min · auth, api-keys, projects

Level 0Tokenizer
0 XP0/54 lessons0/10 achievements
0/120 XP to next level120 XP to go0% complete

All OpenAI API calls use HTTP Bearer authentication. The API key is passed in the Authorization header.

API Key Types

  • Project-scoped keys (sk-proj-...) — Scoped to a single project. Recommended for production.
  • Legacy user keys (sk-...) — Access all projects the user belongs to.
  • Organization ID — Required when a user belongs to multiple organizations.

HTTP Headers

Never hard-code API keys in source code. Use environment variables, secret managers, or vault services. Project-scoped keys (sk-proj-...) are preferred because they limit blast radius if compromised.

Per-environment keys, per-tenant if needed

The minimum is one project per environment (dev / staging / prod) with one key each. That gives you per-environment rate limits, per-environment budgets, and per-environment dashboards. The key for prod has a tiny attack surface (only your production code reads it) so a leak from a dev laptop doesn't drain prod money.

For multi-tenant SaaS, a per-tenant key is overkill but a per-tenant ledger is mandatory — see the Production track. Keys are about isolation; ledgers are about attribution. They solve different problems.

Code

API key from environment·python
import os
from openai import OpenAI

# Option 1: Automatic (reads OPENAI_API_KEY env var)
client = OpenAI()

# Option 2: Explicit with org and project scoping
client = OpenAI(
    api_key=os.environ["OPENAI_API_KEY"],
    organization="org-XXXXXXXXXXXXXXXX",
    project="proj_XXXXXXXXXXXXXXXX",
)
Per-project key with org scoping·text
Authorization: Bearer sk-proj-...
OpenAI-Organization: org-XXXXXXXXXXXXXXXX
OpenAI-Project: proj_XXXXXXXXXXXXXXXX

External links

Exercise

Set up two project-scoped keys: one for dev (low rate limit, $5 monthly cap) and one for prod (higher limit). Wire your script to pick the right one via OPENAI_PROJECT env var. Write a 5-line README that documents the rotation procedure.

Progress

Progress is local-only — sign in to sync across devices.
Spotted a bug or have feedback on this page?Report an Issue

Comments 0

🔔 Reply notifications (sign in)
Sign inPlease sign in to comment.

No comments yet — be the first.