Authentication & SDK Setup
From the course OpenAI API Masterclass
Getting Started with the OpenAI API
The OpenAI API powers some of the most capable AI models available. This lesson covers everything you need to go from zero to making your first API call.
API Key Management
Your API key is the gateway to OpenAI's models. Treat it like a password:
- Create keys in the OpenAI dashboard under API Keys
- Use environment variables — never hardcode keys in source code
- Rotate regularly — create new keys and deprecate old ones
- Set usage limits — configure spending caps per key and per project
// Good: environment variable
const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });
// Bad: hardcoded
const openai = new OpenAI({ apiKey: "sk-..." });
SDK Installation
The official Node.js SDK provides type-safe access to all endpoints:
npm install openai
The Python SDK mirrors the same interface:
pip install openai
Organization & Project Structure
OpenAI supports organizations and projects for team management:
- Organizations group billing and team members
- Projects isolate API keys and usage tracking
- Rate limits apply per-organization and can be customized
Error Handling Patterns
Production applications must handle API errors gracefully:
- 429 Too Many Requests — implement exponential backoff
- 500 Internal Server Error — retry with delay
- 401 Unauthorized — check API key validity
- 400 Bad Request — validate inputs before sending
Project Isolation Best Practice
Use separate OpenAI Projects for each product or environment (dev, staging, prod). Each project gets its own API key and usage quota. This prevents a runaway script in development from consuming your production budget, and makes cost attribution straightforward when reviewing the dashboard. Create a dedicated service account key per project — never share a single key across multiple codebases.
Exponential Backoff Implementation
async function callWithRetry(fn: () => Promise<any>, maxRetries = 5) {
for (let attempt = 0; attempt < maxRetries; attempt++) {
try {
return await fn();
} catch (err: any) {
if (err.status === 429 || err.status >= 500) {
const delay = Math.min(1000 * Math.pow(2, attempt) + Math.random() * 100, 30000);
await new Promise(r => setTimeout(r, delay));
} else {
throw err; // 400/401 are not retryable — fix the request
}
}
}
throw new Error("Max retries exceeded");
}
Pitfall: retrying on 400 errors wastes quota and masks bugs. Only retry on 429 and 5xx.
Key Takeaways
- •Store API keys in environment variables, never in code
- •Use the official SDK for type safety and automatic retries
- •Configure spending limits and rate limit handling
- •Structure projects with organizations for team management
Progress is kept in this browser only.