How to Use the ChatGPT API: Beginner's Guide

Your first API call to GPT-4 in 10 minutes

Ad placeholder (leaderboard)

What the ChatGPT API lets you do

The ChatGPT API gives your own code the same model that powers ChatGPT. Instead of typing into a chat window, you send a request with your messages and get the model’s reply back as data you can use in an app, a script, or an automation. The core endpoint is chat completions: you provide a list of messages — a system message that sets the assistant’s behaviour, a user message with the actual input, and optionally prior assistant turns — and the API returns the next message plus a token-usage breakdown. The generator below builds your first working call in Python, JavaScript, or cURL.

How it works

Three pieces make a call. First, an API key: create one at platform.openai.com after adding billing, then store it as an environment variable like OPENAI_API_KEY — never hard-code it or ship it to the browser. Second, the request: a model name, your messages array, and parameters such as temperature (creativity) and max_tokens (output cap). Third, the response: the model’s message and a usage object telling you exactly how many input and output tokens you spent. You pay per token at a per-million rate that depends on the model, so reading usage after each call keeps cost visible. Start with a small, cheap model like GPT-4o mini — it handles most tasks for a fraction of the price.

Tips and common errors

Fill in the generator above and copy the snippet for your language to make your first call in minutes. As you build, expect a few standard errors: a 401 means your key is wrong or missing, a 429 means a rate limit or no billing credit, and a context-length error means your input plus requested output exceeds the model’s token window. Wrap every call in error handling, read the message the API returns, and add retries with exponential backoff for 429 and 5xx responses so transient failures recover on their own. Once your first call works, the natural next steps are grounding the model in your own data — see building an LLM knowledge base — and choosing the right provider for the job, covered in ChatGPT vs Claude vs Gemini.

Ad placeholder (rectangle)