ChatGPT API Tutorial: Get Started in 10 Minutes
The ChatGPT API (officially the OpenAI Chat Completions API) lets you integrate the same language model that powers ChatGPT directly into your own applications, scripts, and workflows. Unlike the ChatGPT web interface, the API gives you programmatic control: you can set the system prompt, chain multiple requests, process thousands of documents in a loop, build custom chatbots, or embed AI text generation anywhere in your codebase.
This tutorial is designed for developers who want to make their first API request as fast as possible. We will cover getting your API key, installing the SDK, writing your first Python request, understanding the response structure, using curl, managing costs with token awareness, and handling the errors you will inevitably encounter. By the end you will have a working integration and a solid understanding of how to use it responsibly in production. This guide targets the keywords chatgpt api tutorial, openai api tutorial, and how to use chatgpt api.
Prerequisites
Before you begin this OpenAI API tutorial, make sure you have the following:
- Python 3.7 or higher. Run
python --versionorpython3 --versionin your terminal to confirm. The OpenAI Python SDK requires Python 3.7+ and works best on 3.9+. - An OpenAI account. Sign up at platform.openai.com if you do not already have one.
- A payment method on file. The ChatGPT API is a paid service. New accounts receive a small free credit (typically $5–$18 depending on promotion), but a credit card must be added to your account before API keys will work in production. There is no ongoing free tier for API access.
- pip for installing the SDK. It comes pre-installed with Python 3.4+.
Step 1: Get Your API Key
Your API key is a secret token that authenticates your requests to OpenAI's servers. Here is how to generate one:
- Log in at platform.openai.com.
- Click your profile icon in the top-right corner and select API keys from the dropdown, or navigate directly to
platform.openai.com/api-keys. - Click Create new secret key.
- Give your key a descriptive name (e.g.,
my-chatbot-dev) so you can identify it later. - Copy the key immediately — OpenAI will only show it once. If you miss it, you will need to create a new key.
Your key will look like this: sk-proj-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
Security warning: Never paste your API key directly into code that will be committed to version control or shared publicly. We cover how to handle it safely in the Best Practices section below.
Step 2: Install the OpenAI Python SDK
OpenAI maintains an official Python library that wraps the REST API with a clean interface. Install it using pip:
pip install openai
If you are working inside a virtual environment (recommended), activate it first:
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
pip install openai
To verify the installation:
python -c "import openai; print(openai.__version__)"
You should see a version number like 1.30.0 or higher. The SDK reached v1.0 in late 2023 and the interface changed significantly from v0.x, so if you are working from older tutorials make sure examples use the new OpenAI() client style shown below.
Step 3: Make Your First Request
Here is a complete working Python script that sends a message to GPT-4o and prints the response. Replace YOUR_API_KEY_HERE with your actual key (we will fix this properly in the Best Practices section):
from openai import OpenAI
client = OpenAI(api_key="YOUR_API_KEY_HERE")
response = client.chat.completions.create(
model="gpt-4o",
messages=[
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "What is the capital of France?"
}
]
)
print(response.choices[0].message.content)
Run this script with python your_script.py. You should see a response like "The capital of France is Paris."
Let us break down what this code does:
OpenAI(api_key=...)initialises the client with your credentials.client.chat.completions.create()calls the Chat Completions endpoint — the same one used by ChatGPT.model="gpt-4o"specifies which model to use. You can also use"gpt-4o-mini"for a cheaper, faster option.- The
messageslist is a conversation history. Thesystemrole sets the AI's behaviour, anduseris the message from your end user. response.choices[0].message.contentextracts the text of the reply.
Step 4: Understand the Response Structure
The API returns a structured response object. Here is what the full JSON looks like (simplified for clarity):
{
"id": "chatcmpl-abc123",
"object": "chat.completion",
"created": 1717200000,
"model": "gpt-4o-2024-05-13",
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": "The capital of France is Paris."
},
"finish_reason": "stop"
}
],
"usage": {
"prompt_tokens": 23,
"completion_tokens": 10,
"total_tokens": 33
}
}
The key fields you will use in most applications:
choices[0].message.content— the actual text of the model's response.choices[0].finish_reason— why the model stopped. Common values:"stop"(natural end),"length"(hit max_tokens limit),"content_filter"(blocked by safety system).usage.total_tokens— the total number of tokens consumed by this request (input + output). This is what you are billed for.
In Python with the SDK, these map to attributes directly:
# Access the response text
text = response.choices[0].message.content
# Check why the model stopped
finish_reason = response.choices[0].finish_reason
# See token usage
tokens_used = response.usage.total_tokens
print(f"Response: {text}")
print(f"Tokens used: {tokens_used}")
Step 5: Try with curl
You do not need the Python SDK to make an OpenAI API request. Here is the equivalent request using curl, which works in any terminal:
curl https://api.openai.com/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_API_KEY_HERE" \
-d '{
"model": "gpt-4o",
"messages": [
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "What is the capital of France?"
}
]
}'
The curl approach is useful for quick testing, integration from non-Python languages, or when debugging whether an issue is in your code or in the API call itself. Any HTTP client library in any language — Node.js fetch, Ruby's Net::HTTP, Go's http package — can make this request by following the same structure.
Understanding Tokens and Costs
The ChatGPT API is billed per token, not per request. A token is roughly 4 characters of English text, or about 0.75 words. The sentence "The capital of France is Paris" is approximately 8 tokens. Understanding token consumption is critical for managing costs at scale.
As of mid-2026, GPT-4o is priced at approximately $2.50 per million input tokens and $10.00 per million output tokens. GPT-4o mini is significantly cheaper at $0.15 per million input tokens. For most applications, GPT-4o mini provides an excellent quality-to-cost ratio for simple tasks.
You can estimate token counts before sending a request using the tiktoken library:
pip install tiktoken
import tiktoken
enc = tiktoken.encoding_for_model("gpt-4o")
text = "What is the capital of France?"
tokens = enc.encode(text)
print(f"Token count: {len(tokens)}")
Use our token calculator to estimate costs for your specific use case without writing any code. See also our guide to understanding AI tokens for a deeper explanation, and our post on how to reduce AI API costs for practical optimisation strategies.
Handling Errors
Production applications must handle API errors gracefully. The most common errors you will encounter when using the ChatGPT API are:
- AuthenticationError (401): Invalid or missing API key. Check your key is correct and not expired.
- RateLimitError (429): You have hit your requests-per-minute or tokens-per-minute limit. Implement exponential backoff.
- BadRequestError (400): Your request is malformed — check your messages array structure.
- APIConnectionError: A network issue prevented the request from reaching OpenAI's servers.
- InternalServerError (500): A problem on OpenAI's side. Retry with backoff.
Here is a robust error-handling pattern using try/except:
from openai import OpenAI, AuthenticationError, RateLimitError, BadRequestError
import time
client = OpenAI(api_key="YOUR_API_KEY_HERE")
def call_api_with_retry(messages, max_retries=3):
for attempt in range(max_retries):
try:
response = client.chat.completions.create(
model="gpt-4o",
messages=messages
)
return response.choices[0].message.content
except AuthenticationError:
print("Error: Invalid API key. Check your credentials.")
raise # Do not retry auth errors
except RateLimitError:
wait_time = 2 ** attempt # Exponential backoff: 1s, 2s, 4s
print(f"Rate limit hit. Waiting {wait_time} seconds...")
time.sleep(wait_time)
except BadRequestError as e:
print(f"Bad request: {e}")
raise # Do not retry malformed requests
raise Exception("Max retries exceeded")
# Usage
messages = [{"role": "user", "content": "Hello, world!"}]
result = call_api_with_retry(messages)
print(result)
The exponential backoff pattern is important for rate limit errors. Hammering the API immediately after receiving a 429 will just produce more 429s. The standard practice is to wait 1 second, then 2, then 4, doubling each time.
Best Practices
Following these best practices from the start will save you security incidents and unnecessary costs:
Use Environment Variables for Your API Key — Never Hardcode It
Hardcoding your API key in source code is the single most common mistake developers make. It is all too easy to accidentally commit it to a public GitHub repository. Instead, store it as an environment variable:
# On macOS/Linux, add to your ~/.zshrc or ~/.bashrc:
export OPENAI_API_KEY="sk-proj-your-key-here"
# On Windows (Command Prompt):
set OPENAI_API_KEY=sk-proj-your-key-here
Then in Python, you can omit the api_key argument entirely — the SDK reads it from the environment automatically:
from openai import OpenAI
# The SDK automatically reads OPENAI_API_KEY from the environment
client = OpenAI()
response = client.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": "Hello!"}]
)
print(response.choices[0].message.content)
For projects, use a .env file with the python-dotenv library. Always add .env to your .gitignore before committing anything.
pip install python-dotenv
from dotenv import load_dotenv
import os
from openai import OpenAI
load_dotenv() # Loads variables from .env file
client = OpenAI(api_key=os.environ.get("OPENAI_API_KEY"))
Set Usage Limits on the OpenAI Dashboard
In your OpenAI account settings under Billing → Usage limits, you can set a hard monthly spending cap. This prevents unexpected bills if a bug causes your application to send requests in an infinite loop.
Use the Cheapest Model That Meets Your Quality Bar
GPT-4o is powerful, but GPT-4o mini handles most routine tasks (classification, summarisation, simple Q&A) at a fraction of the cost. Benchmark your specific use case with both models before committing to the more expensive one. Our token calculator can help you model cost projections.
Cache Repeated Responses
If your application sends the same (or very similar) prompts repeatedly, cache the responses with Redis or a simple dictionary. There is no reason to pay for the same API call ten times.
Frequently Asked Questions
How do I get a ChatGPT API key?
Log in to platform.openai.com, go to the API keys section, and click "Create new secret key." You need a payment method on file before the key will work beyond the free credit limit. The key is only shown once — copy it immediately and store it securely.
Is the ChatGPT API free?
Not permanently. New OpenAI accounts receive a small amount of free credit (typically $5–$18) that can be used for testing. After the free credit is exhausted, all API usage is billed by token. There is no free tier for the API — the free ChatGPT web interface and the paid API are entirely separate products.
How much does the ChatGPT API cost per request?
Cost depends on the model and the number of tokens in your request and response. As of 2026, GPT-4o costs approximately $2.50 per million input tokens and $10.00 per million output tokens. A typical 500-word article generation (roughly 700 tokens input + 700 tokens output) would cost approximately $0.009 with GPT-4o or significantly less with GPT-4o mini. Use our token calculator to estimate costs for your specific prompts.
What is the rate limit for ChatGPT API?
Rate limits vary by your account tier and the model you are using. New accounts start at Tier 1 with limits like 500 requests per day and 30,000 tokens per minute for GPT-4o. As you spend more, your tier increases and limits are raised automatically. You can check your current limits at platform.openai.com/account/limits. For high-volume production applications, contact OpenAI to request higher limits.
Can I use the ChatGPT API for free?
You can test the API using the free credit provided to new accounts, which typically lasts for a few weeks of light development use. For ongoing production use, payment is required. Some developers use the free ChatGPT web interface for manual testing and reserve API calls for automated workflows to manage costs during development.