Step-by-step guide

OpenAI API key setup guide

Create your account, generate an API key, configure billing, test your connection, and start building. Ready in 5 minutes.

Developer configuring OpenAI API key setup on laptop

Setting up an OpenAI API key takes about five minutes. Here is the complete walkthrough.

This guide walks you through every step of setting up an OpenAI API key, from creating your account to running your first API call. By the end, you will have a working key, a configured billing method, and a verified connection. If you are a developer building with LLMs, this is the first thing you need.

We cover the official OpenAI path and a cost-controlled alternative at the end for teams that want predictable spending. Everything below applies to direct OpenAI access unless stated otherwise.

Step 1: Create an OpenAI account

Go to platform.openai.com and click Sign up. You can register with an email address or use single sign-on through Google, Microsoft, or Apple.

If you already use ChatGPT, the same account works for the API platform. The login is shared, but billing is completely separate. A ChatGPT Plus or Pro subscription does not include API credits, and your API usage does not change your ChatGPT plan. You still need to add a payment method in the API billing section even if you pay for ChatGPT.

After signing up, verify your email address. OpenAI may request phone verification for new accounts. This is a one-time step and does not affect your API usage limits or billing.

Once you are logged in, you land on the API platform dashboard. From here, all configuration happens through the Settings menu.

Step 2: Navigate to API Keys

You need to find the API Keys page before you can generate a key. There are two ways to get there:

  1. Through the menu: Click your profile icon in the top right corner, select Settings from the dropdown, then click API keys in the left sidebar.
  2. Direct URL: Visit platform.openai.com/api-keys to skip the navigation steps entirely.

The API Keys page shows every key you have created, when it was last used, and when it was created. If this is your first time, the list is empty. The page also shows your current project — if you have multiple projects, make sure the correct one is selected before creating a key.

OpenAI organizes keys by project, so keys created under one project cannot be used in another. For most individual developers, the default project is fine. Teams with multiple products or environments typically create separate projects and separate keys for each.

Step 3: Create your secret key

Click Create new secret key. A dialog appears with a few fields:

Click Create secret key. OpenAI shows the full key exactly once, in the format sk-proj-.... Copy it immediately and store it in a secure location — a password manager, an environment variable file, or a secrets vault like AWS Secrets Manager or HashiCorp Vault.

After you close this dialog, the full key is gone. OpenAI only displays a masked version (like sk-proj-...xxxx) from that point forward. There is no way to recover a secret key that was not copied. If you lose it, delete it and generate a new one.

Pro tip: Name your keys before creation. A key named "production-api" is immediately obvious on the dashboard. An unnamed key is not.

Step 4: Add a payment method

API calls require a funded account. Go to Settings → Billing to add a credit or debit card. OpenAI uses postpaid billing: you consume tokens during the month and pay for what you used when the billing cycle ends.

New accounts sometimes receive a small amount of free credit — typically $5 to $18, depending on the current promotion. This credit covers your first API calls and does not require a card. Once it runs out, you need a payment method to continue.

Before making any significant API calls, set a usage limit (also called a hard limit) on your billing page. This caps your monthly spend and prevents surprise invoices from runaway scripts or unexpected traffic spikes. If your usage hits the limit, API calls are rejected until you raise the limit or the next billing cycle begins.

OpenAI also offers auto-recharge: when your balance drops below a set threshold, it automatically tops up your account with a predetermined amount. This is optional but useful for production workloads where downtime from an empty balance would be costly. For testing and development, manual billing with a hard limit is usually sufficient.

Check your billing page regularly. The usage dashboard updates with a slight delay, so real-time visibility requires logging token counts in your own application.

Step 5: Test your connection

The fastest way to verify that your key works is with a curl command. Open a terminal and run the following, replacing YOUR_API_KEY with the key you just created:

curl https://api.openai.com/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -d '{
    "model": "gpt-4o-mini",
    "messages": [
      {"role": "user", "content": "Say hello in one sentence."}
    ]
  }'

A successful request returns a JSON response containing the model's reply. If you receive a 401 Unauthorized error, the key is invalid or has been deleted. A 429 Too Many Requests error means you have hit a rate limit or your account has no remaining credits.

Python example

Install the official OpenAI Python SDK, then run a quick test script:

pip install openai
from openai import OpenAI

client = OpenAI(api_key="YOUR_API_KEY")

response = client.chat.completions.create(
    model="gpt-4o-mini",
    messages=[{"role": "user", "content": "Say hello in one sentence."}]
)

print(response.choices[0].message.content)

The SDK automatically sets the base URL to https://api.openai.com/v1. You do not need to configure it unless you are using a third-party compatible endpoint. The same pattern works across all OpenAI-compatible tools — coding agents, CLI utilities, and custom applications.

Node.js example

The process is nearly identical for JavaScript and TypeScript projects. Install the OpenAI npm package, initialize the client with your key, and call the chat completions endpoint:

npm install openai
import OpenAI from "openai";

const client = new OpenAI({ apiKey: "YOUR_API_KEY" });

const response = await client.chat.completions.create({
  model: "gpt-4o-mini",
  messages: [{ role: "user", content: "Say hello in one sentence." }],
});

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

All three approaches — curl, Python, and Node.js — hit the same endpoint and return the same response format. If one works, your key is configured correctly for all tools that speak the OpenAI protocol.

Step 6: Choose the right model

OpenAI offers several model families, each at a different price point and capability level. Choosing the right one for your workload is the single biggest factor in your API costs.

ModelBest forInput (per 1M tokens)Output (per 1M tokens)
GPT-5.4 MiniTesting, classification, simple completions$0.75$4.50
GPT-5.4General-purpose production workloads$2.50$15.00
GPT-5.6 SolCoding agents, multi-step reasoning$5.00$30.00
GPT-6 AstraComplex analysis, large-context tasks$10.00$50.00
GPT-5.3 Codex SparkCode generation, developer tooling$1.75$14.00

Source: OpenAI official pricing, September 2026.

Start with GPT-5.4 Mini for testing and development. It costs almost nothing per request and is fast. Move to GPT-5.4 when you need better reasoning for production traffic. Reserve GPT-5.6 Sol and GPT-6 Astra for tasks that genuinely require frontier intelligence — complex code generation, multi-step analysis, and large-context workloads. A single 30-minute coding session on a premium model can consume millions of tokens, so the model choice directly affects your monthly bill.

For coding agents specifically, the practical strategy is model routing: use Mini for autocomplete and simple edits, Sol or Codex Spark for architecture decisions and complex refactors, and Astra only when the codebase context is too large for the others. This approach typically reduces average cost per session by 60-80% compared to using the most expensive model for everything.

Common setup issues and troubleshooting

401 Unauthorized error. Your API key is invalid, expired, or has been deleted. Go to the API Keys page and verify the key exists. If in doubt, delete it and create a new one.

429 Too Many Requests error. You have exceeded the rate limit for your account tier, or your prepaid balance is empty. Check your usage dashboard and either wait for the rate limit to reset or add funds.

402 Payment Required error. Your account has no remaining credits and no payment method on file. Add a credit card under Settings → Billing to continue.

Key works in curl but not in a library. Check that you are passing the key correctly. The Python SDK expects it as api_key="sk-..." or via the OPENAI_API_KEY environment variable. The Node.js SDK accepts it in the constructor options. Do not include the "Bearer " prefix when using SDKs — the libraries add it automatically.

Wrong base URL. The default base URL is https://api.openai.com/v1. Most SDKs set this automatically. If you are using a third-party provider, replace this with their endpoint but keep the rest of the request format identical.

Key committed to a git repository. Delete the key immediately from the OpenAI dashboard and create a new one. Add your API key to .gitignore (or use a .env file that is already ignored) and use environment variables instead. Check your git history for exposed secrets and consider rotating the key even if you force-push the removal.

Unexpected charges from testing. If you forgot to set a usage limit, a test loop or a large-context request can generate a significant bill. Set a hard limit as soon as you create your account — before making any API calls. This takes 30 seconds and can save hundreds of dollars.

Alternative: APItokendeal setup

If you want OpenAI-compatible API access with predictable spending and no postpaid billing surprises, APItokendeal is an alternative worth considering. The setup takes about the same amount of time and the request format is identical — the only differences are the base URL and how you pay.

APItokendeal gives you access to 30+ models — including GPT, Claude, DeepSeek, Gemini, Kimi, and Qwen — through a single API key. Instead of postpaid billing (where you pay for whatever you consume at the end of the month), APItokendeal uses prepaid token packs. You buy a balance upfront, spend against it, and top up when it runs out. Your maximum monthly spend is determined at the time of purchase, not estimated after the fact.

  1. Sign up at apitokendeal.com/register — you get 2.5M free tokens instantly
  2. Copy your API key from the account dashboard
  3. Configure your tool — set the base URL to https://api.apitokendeal.com/v1 and paste your API key

The request format is identical to OpenAI. Tools like Cline, Claude Code, OpenCode, Codex, and any other OpenAI-compatible client work without code changes — just swap the base URL and key.

FeatureOpenAI DirectAPItokendeal
BillingPostpaid (pay after)Prepaid (pay before)
Cost ceilingManual limit (you set it)Hard ceiling (prepaid balance)
Model familiesOpenAI onlyOpenAI, Claude, DeepSeek, Gemini, Kimi, Qwen + more
Free tier$5–$18 credit (varies)2.5M tokens on signup
Cost vs officialFull priceUp to 70% off with token packs
Setup time5 minutes5 minutes

Token packs start at $9.99 for 10M tokens. See full pricing for all tiers.

If cost predictability and multi-model access matter more than using OpenAI's infrastructure directly, the switch is straightforward — your code stays the same, only the endpoint and key change.

Ready to start building?

Get your API key instantly. Start with 2.5M free tokens, then choose a token pack when you are ready for production.