Master Code
On The Go

Learn. Practice. Build.

How-To Guide

OpenAI API Setup

Every AI app starts with an API key. Here's how to get one and make your first request in 10 minutes.

📋 What You'll Need

Cost warning: The OpenAI API is NOT free. You pay per token. But most hobby projects cost a few dollars per month. Load $5 to start — that's enough for hundreds of chats.

1

Create an OpenAI Account

Go to the platform:

👉 platform.openai.com

Sign up with email or Google. Verify your email and phone.

2

Add Billing

Go to Settings → Billing. Add a payment method and load a small balance ($5 is plenty).

Set a monthly usage limit so you never get surprised. $10/month is safe for learning.

3

Create an API Key

Go to API Keys → Create new secret key. Give it a name like "My First App".

Copy the key immediately. It looks like sk-... — you'll never see it again.

💡 Store it in .env, not in code. Never commit API keys to GitHub.

4

Install the SDK

Node.js:

npm install openai dotenv

Python:

pip install openai python-dotenv
5

Make Your First Call (Node.js)

Create .env:

OPENAI_API_KEY=sk-your-key-here

Create chat.js:

import 'dotenv/config';
import OpenAI from 'openai';

const openai = new OpenAI({
    apiKey: process.env.OPENAI_API_KEY
});

const response = await openai.chat.completions.create({
    model: 'gpt-4o-mini',
    messages: [
        { role: 'user', content: 'Explain recursion in one sentence.' }
    ]
});

console.log(response.choices[0].message.content);

Run it:

node chat.js

You should see the AI's reply. 🎉

🧠 Essential Concepts

💬 System Prompts Matter

const response = await openai.chat.completions.create({
    model: 'gpt-4o-mini',
    messages: [
        {
            role: 'system',
            content: 'You are a patient programming tutor. Always reply in 2 sentences or less.'
        },
        { role: 'user', content: 'What is a promise?' }
    ],
    temperature: 0.7
});

The system message shapes every reply. This is how you build "chatbots" with personality.

🔧 Troubleshooting

"401 Unauthorized"

Your API key is wrong, expired, or has whitespace. Regenerate it in the dashboard.

"429 Too Many Requests"

You're rate-limited. Slow down, or upgrade your usage tier. Free tier has strict limits.

"insufficient_quota"

You're out of credit. Add funds in Billing.

Accidental key exposure

Immediately revoke the key in API Keys, then generate a new one. Also rotate any other keys that shared the same .env.

🎯 What's Next?

← All How-To Guides