Guides

How to Get an OpenAI API Key in 2026: A 5-Minute Setup Guide

Find the OpenAI API key page, add prepaid credit, set a hard spend limit, store the key safely and make your first GPT-6 call without 401 or 429 errors.

· Updated
· 11 min read
openai tutorial llms api
How to Use the OpenAI API Key for Your Applications
Table of Contents

Your OpenAI API keys live at platform.openai.com/api-keys (also platform.openai.com/settings/organization/api-keys). ChatGPT and the API are billed separately, so a ChatGPT Plus or Pro plan does not fund API calls; if your API account has no free credits, buy prepaid credit first (minimum $5).

TL;DR

StepWhat to doTime
1. Sign upplatform.openai.com, verify email + phone1 min
2. Add billingIf you have no free credits, buy at least $5 of credit (turn auto-reload off or set its optional monthly reload limit) and set a monthly spend limit with Enforce a hard limit on1 min
3. Create keyAPI keys page, Create new secret key, scope to a project, set an expiration date30 sec
4. Store securelySave as OPENAI_API_KEY env var, add .env to .gitignore30 sec
5. First callcurl or pip install openai then client.responses.create2 min
Optional: evaluationtraceAI auto-instruments OpenAI SDK, ships traces to FAGI+5 min

New API accounts use prepaid billing: any free credits are used first, the minimum purchase is $5, the default is $10, and auto-reload is on by default during setup. Your first request returns 200 only after the account has credit, so finish billing before you test the key.

Where Is the OpenAI API Key Page?

Your OpenAI API keys are on the API keys page at platform.openai.com/api-keys, which OpenAI’s newer docs also link as platform.openai.com/settings/organization/api-keys. The page lists your keys, but the full secret is shown only once, when you create it. If you lost a key, create a new one, update your application, then delete the old key with the trash can icon. Deleted keys cannot be used, so any app still sending the old key stops working.

What an OpenAI API key actually is

An OpenAI API key is a long random string that authenticates server-side calls to the OpenAI REST API. Treat it as a bearer secret. Every call your application makes carries the key in an Authorization: Bearer $OPENAI_API_KEY header.

OpenAI uses the key to identify the account and project to bill, the rate limits to apply, and the model access to grant. It is the equivalent of a password for your OpenAI compute budget, which is why it must never appear in client-side code, public repositories, or screenshots.

Keys are not encrypted by themselves. They are bearer tokens, which means anyone who holds the key can use it. Treat them with the same care you would a database admin password.

Create a Platform Account

Open platform.openai.com and sign up. The Platform account is separate from the ChatGPT consumer subscription you may already have. You can sign up with email, Google, Microsoft, or Apple. After email verification, OpenAI may require a phone number for SMS verification depending on your account, region, or risk checks.

Once inside, switch to the project switcher in the top left and create a new project for the workload you are building. Project names are the unit of cost reporting, rate limiting, and key scoping, so name them clearly (for example, customer-support-bot or eval-harness-dev).

Add Credits and Set a Hard Spend Limit

Open the API billing overview at platform.openai.com/account/billing and select Add payment details. Choose your first credit purchase (the minimum is $5 and the default is $10). Before you confirm, review Use auto-reload: it is on by default, so turn it off or set its optional monthly reload limit.

Then go to Organization limits (platform.openai.com/settings/organization/limits). In Spend, select Edit spend limit, enter a Monthly spend limit, turn on Enforce a hard limit and select Save. You can set the same limit for one project under Project settings > Limits.

A spend alert only sends a notification while traffic continues. A hard limit makes requests fail with a 429 error (organization_spend_limit_exceeded or project_spend_limit_exceeded). Enforcement is not instantaneous, so recorded spend can slightly exceed the cap.

Do not skip this step. A runaway prompt loop can drain your credit balance quickly, especially on gpt-6-astra at $50 per 1M output tokens. The hard limit caps the blast radius. Do not treat the prepaid balance as a cutoff: OpenAI says API access may not stop immediately when credits run out and the overage shows as a negative balance.

Create Your OpenAI API Key

Open platform.openai.com/api-keys (also reachable as platform.openai.com/settings/organization/api-keys) and click Create new secret key. Choose:

  • Owner: a service account for automated production workloads, or your own user for local testing.
  • Project: the one you just created.
  • Name: descriptive, for example support-bot-prod.
  • Permissions (user-owned keys only): All (the default), Restricted (None, Read or Write per endpoint) or Read Only. Pick Restricted for a user key; the dialog does not show these controls for service-account keys.
  • Expiration: set an expiration date; OpenAI strongly recommends expiring keys plus a regular rotation process.

Click Create. The dialog shows the full key exactly once. Paste it into your password manager or directly into your environment file before closing the dialog. If you lose the key value, you cannot recover it; you have to create a new one.

Organization and project admins can restrict which key types can be created (only service-account keys, or only user-owned project keys) under API Key Governance. If you work in ChatGPT or Codex, the OpenAI Developers plugin can also create project API keys when your application needs one.

Store the Key as an Environment Variable

Never hardcode the key. The minimum acceptable practice on a developer laptop is a .env file plus .gitignore.

# .env
OPENAI_API_KEY=your_api_key_here
# .gitignore
.env
.env.local
.env.*.local

To set the key for your shell instead, run export OPENAI_API_KEY="your_api_key_here" on macOS or Linux, or setx OPENAI_API_KEY "your_api_key_here" in Windows PowerShell. Each OpenAI SDK automatically reads your API key from the system environment.

For production, use a managed secret store: AWS Secrets Manager, Google Secret Manager, Azure Key Vault, HashiCorp Vault, Doppler, or 1Password Secrets Automation. These rotate keys, audit access, and inject the secret at runtime so it never lives on disk.

If you accidentally push a key to a public repository, revoke it from the Platform dashboard immediately. GitHub secret scanning can detect leaked OpenAI keys in public repositories, but assume the key is already compromised.

Make Your First Request

These examples use gpt-6-luna, which OpenAI recommends for cost-sensitive, high-volume workloads; switch to gpt-6-astra, OpenAI’s flagship, for complex reasoning and coding. If you still call the gpt-5 snapshot, note that gpt-5-2025-08-07 is scheduled for API shutdown on 11 December 2026.

curl

curl https://api.openai.com/v1/responses \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -d '{
    "model": "gpt-6-luna",
    "input": "Write a haiku about a developer who finally remembered to rotate their API key."
  }'

Python

Install the SDK:

pip install openai python-dotenv

Then:

import os
from dotenv import load_dotenv
from openai import OpenAI

load_dotenv()
client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])

response = client.responses.create(
    model="gpt-6-luna",
    input="Summarize the difference between GPT-6 Astra and GPT-6 Luna in two sentences.",
)
print(response.output_text)

The responses endpoint is the recommended path in modern Python SDK versions. Legacy code that calls openai.ChatCompletion.create (from the pre-1.x Python SDK) does not work in modern SDK versions and should be migrated to client.responses.create or client.chat.completions.create.

Node.js

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

const client = new OpenAI();

const response = await client.responses.create({
  model: "gpt-6-luna",
  input: "Give me three test ideas for an OpenAI integration.",
});

console.log(response.output_text);

Add Evaluation and Observability

A working key tells you nothing about whether the model is producing correct answers, hallucinating, drifting after a model update, or quietly burning budget on retries. The gap between “the API call succeeded” and “the response was good” is where production AI bugs hide.

Future AGI ships two open source packages that close this gap and pair directly with the openai SDK:

  • traceAI is an OpenTelemetry-based auto-instrumentation library. One import wraps the openai client and emits a structured trace per call, including prompt, response, model, tokens, latency, cost, and tool calls.
  • agent-learning-kit (formerly ai-evaluation, pip install agent-learning-kit) runs evaluators against those traces. Future AGI has custom evals, so you can write your own grading rule or use built-in checks such as context adherence, groundedness, tone, toxicity and PII leakage.

Both are Apache 2.0. Create FI_API_KEY and FI_SECRET_KEY in the Future AGI dashboard, and add them alongside OPENAI_API_KEY in your .env:

# .env
OPENAI_API_KEY=your_api_key_here
FI_API_KEY=...
FI_SECRET_KEY=...

Then load them and register the tracer:

import os
from dotenv import load_dotenv

load_dotenv()  # loads OPENAI_API_KEY, FI_API_KEY, FI_SECRET_KEY

from fi_instrumentation import register
from fi_instrumentation.fi_types import ProjectType
from traceai_openai import OpenAIInstrumentor

trace_provider = register(
    project_type=ProjectType.OBSERVE,
    project_name="openai-getting-started",
)

OpenAIInstrumentor().instrument(tracer_provider=trace_provider)

# Use openai normally; every call is now traced
from openai import OpenAI
client = OpenAI()
response = client.responses.create(
    model="gpt-6-luna",
    input="Explain prompt caching in one paragraph.",
)
print(response.output_text)

From here, every openai call in the process is traced without further code changes, and the traceAI repository uses the same instrumentor pattern for other frameworks such as LangChain and Anthropic. For a multi-step agent, see our guide to instrumenting a full agent with traceAI.

Future AGI traceAI trace view showing an agent span tree, a selected tool span with status, duration, token counts and cost, and its span attributes on a dark background

To score the output, add an evaluator:

from fi.evals import evaluate

result = evaluate(
    "context_adherence",
    output=response.output_text,
    context="The OpenAI API bills input and output tokens separately.",
)
print(result.score)
print(result.reason)

In Future AGI Observe, attach evals to whole traces or single spans and set alerts on regressions. When content needs blocking, put Agent Command Center in front of the OpenAI call: change base_url to https://gateway.futureagi.com and turn on guardrail checks such as prompt injection and PII detection.

Is the OpenAI API Key Free?

Creating an OpenAI API key costs nothing, but every request is billed. New API accounts use prepaid billing: any free credits are used first, then purchased credit. The minimum purchase is $5 and the default is $10. Purchased credits expire after 1 year and are non-refundable unless required by law or contract, or an approved exception applies.

ChatGPT and the API platform have separate billing systems, so a ChatGPT Plus or Pro plan does not cover API calls. Skip any site offering a free OpenAI API key: sharing API keys is against OpenAI’s Terms of Use.

Rate limits, retries, and cost control

OpenAI returns HTTP 429 when you exceed requests per minute (RPM) or tokens per minute (TPM) for your tier; see how OpenAI rate limits behave under load. Paid usage tiers are Build, Launch and Grow. You move up automatically when total credit purchases reach $5, $100 and $500, with monthly usage limits of $500, $5,000 and $200,000. Check Settings > Organization > Limits for your per-model rate limits.

OpenAI API usage tiers Build, Launch and Grow with the total credit purchase that qualifies for each tier and its monthly usage limit

SymptomCauseFix
401 Invalid Authentication or Incorrect API key providedWrong, mistyped or revoked key, or a key from a different organization or projectCopy the full key again or create a new one, then update OPENAI_API_KEY
401 IP not authorizedRequest IP is not on your IP allowlistSend from an allowlisted IP or update the allowlist
403 Country, region, or territory not supportedRequest from an unsupported locationCall the API from a supported country or region
429 credit_balance_exhausted or *_spend_limit_exceeded or organization_usage_limit_exceededNo prepaid credit, a hard spend limit hit, or the approved usage limit hitAdd credit or raise the limit; retrying will not help
429 Rate limit reached or slow_downRequests or tokens sent too quicklyFollow Retry-After when present, back off, then retry
500 Server errorIssue on OpenAI’s serversRetry after a brief wait
503 server_is_overloadedModel temporarily overloadedFollow Retry-After when present, then retry
Empty output_textRefusal or stopped generationInspect response.output[0].content

Use exponential backoff with jitter for rate-limit 429s and 5xx errors, follow the Retry-After header when present, and read x-request-id from the response headers so OpenAI support can trace a failure if you escalate. Billing and spend-limit 429s need a different fix: add credit or raise the limit, because a retry fails the same way.

For cost, these are the controls to set first:

  • Use the cheapest model that passes your eval. Try the efficient GPT-6 Luna tier first for classification and extraction, and move up only if it fails your eval. Our LLM pricing and cost comparison lines up the alternatives.
  • Cache prompt prefixes. OpenAI prompt caching cuts input token cost on repeated system prompts.
  • Batch where latency allows. The batch endpoint discounts non-urgent jobs.
  • Trim history. Every earlier turn you resend is billed again as input tokens.
  • Set project spend alerts. An alert only notifies you while traffic continues, so pair it with the hard spend limit you set earlier.

Security and compliance checklist

  • Use service-account keys, not user-owned keys, for production applications.
  • Rotate keys on a schedule and immediately after any departure or suspicious activity.
  • Store keys in a managed secret store in production. Inject at runtime, never write to disk.
  • Restrict each key to the endpoints the app actually uses.
  • Turn on IP allowlisting so requests from other IP addresses are rejected, even with a valid key.
  • Where supported, use workload identity federation to get short-lived access tokens instead of storing a long-lived key.
  • Revoke a leaked or unused key at once; OpenAI says revocations take effect within a few seconds.
  • Log only the prompt, response, and metadata you have a legal basis to retain; never log the key itself.
  • Send data only over HTTPS, which the SDK does by default.
  • Match your data handling to OpenAI’s usage policies, especially around prohibited content and PII.
  • Run a guardrail layer (Future AGI Agent Command Center, NeMo Guardrails, or your own) when the model output goes to end users.

Common errors and fixes

”Invalid API key” right after creating one

You may have pasted a truncated copy. The full key is the entire string shown in the Create dialog. Recreate the key and copy the full value before closing the dialog.

429 Errors From an Exhausted Credit Balance or Spend Limit

Read error.code in the response. credit_balance_exhausted means the organization has no prepaid credit left, so buy credit from its API billing overview. organization_spend_limit_exceeded or project_spend_limit_exceeded means a hard spend limit was reached, so raise or remove it.

organization_usage_limit_exceeded means the OpenAI-assigned usage limit was reached, so request a higher approved limit. Retrying these errors won’t restore access.

”Model does not exist or you do not have access”

Check the model ID against OpenAI’s models page. OpenAI may also ask you to complete verification before you can use certain products, features or models.

Leaked key in a public repo

Revoke immediately, generate a new one, and audit usage for unexpected spend. GitHub secret scanning can detect leaked OpenAI keys in public repositories, but assume the key is already compromised.

From a Working Key to a Production-Ready OpenAI App

Five minutes in, you have a project key with an expiration date, a hard spend limit, the key stored as OPENAI_API_KEY and a first response printed from gpt-6-luna. The next question is whether those responses are any good, so trace and score every call with the Future AGI Observe quickstart.

Frequently Asked Questions

How do I get the OpenAI API key?

Sign in at platform.openai.com, open the API keys page, click Create new secret key, name it, assign it to a project and copy it immediately. OpenAI shows the full secret only once. If your account has no free credits, add prepaid credit in billing (minimum $5) before your first request will succeed.

Is OpenAI API key available for free?

Creating an OpenAI API key is free, but every API call is billed, first against any free credits on your account and then against prepaid credit. The minimum credit purchase is $5. A ChatGPT Plus or Pro subscription does not pay for API calls, because ChatGPT and the API platform have separate billing systems.

How much does the OpenAI API cost?

OpenAI API pricing is per million tokens: GPT-6 Luna costs $0.10 input and $0.50 output, GPT-6.1 Sol $2 and $10, and GPT-6 Astra $10 and $50. Those are standard list prices for OpenAI's three recommended models as of October 2026. Batch processing halves them, and purchased credits expire after one year.

What is an OpenAI API key used for?

An OpenAI API key authenticates your code's requests to OpenAI models and ties each call to an organization and project for billing and limits. Every official SDK reads it from the OPENAI_API_KEY environment variable, and a wrong key returns a 401 error. Future AGI traceAI instruments the OpenAI SDK so every keyed call is traced.

How do I find out my OpenAI API key?

Your OpenAI API keys are listed on the API keys page at platform.openai.com/api-keys, but the full secret is shown only once, when you create it. If you lost it, create a new key, update your application, then delete the old key with the trash can icon. Revocations take effect within a few seconds.

Do OpenAI API keys expire?

OpenAI project API keys can be created with an expiration date, after which any request using that key is rejected, and OpenAI strongly recommends setting one. Before a key expires, create a replacement, update your apps and revoke the old key. Separately, purchased API credits expire after one year.

Why is my OpenAI API key not working?

A failing OpenAI API key returns 401 for an invalid or revoked key, 429 for exhausted credit or a hit limit, or 403 for an unsupported region. Read the error code in the response. Retrying billing or spend-limit errors will not help until you add credit or raise the limit.
Related Articles
View all