ChatGPT API: Complete Guide
The OpenAI API provides access to the GPT-4o, GPT-4o-mini and o1 models. It is the foundation for AI chatbots, content generation and task automation.
Getting an API Key
Sign up at platform.openai.com, top up your balance ($5+) and create an API key. Keep the key in environment variables.
First Request (cURL)
curl https://api.openai.com/v1/chat/completions -H "Content-Type: application/json" -H "Authorization: Bearer $OPENAI_API_KEY" -d '{
"model": "gpt-4o-mini",
"messages": [
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "What is VPS hosting?"}
],
"max_tokens": 500
}' PHP Integration
composer require openai-php/client <?php
require 'vendor/autoload.php';
$client = OpenAI::client($_ENV['OPENAI_API_KEY']);
$response = $client->chat()->create([
'model' => 'gpt-4o-mini',
'messages' => [
['role' => 'system', 'content' => 'You are a ZevsHost support assistant.'],
['role' => 'user', 'content' => 'How do I add a domain in cPanel?'],
],
'max_tokens' => 800,
]);
echo $response->choices[0]->message->content; Python Integration
pip install openai from openai import OpenAI
client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[{"role": "user", "content": "Explain VPS in 3 sentences."}],
max_tokens=200
)
print(response.choices[0].message.content) Streaming (streamed output)
stream = client.chat.completions.create(
model="gpt-4o-mini",
messages=[{"role": "user", "content": "Write an article about VPS"}],
stream=True
)
for chunk in stream:
if chunk.choices[0].delta.content:
print(chunk.choices[0].delta.content, end="", flush=True) Pricing and Models (2025)
| Model | Input (1M) | Output (1M) | Use case |
|---|---|---|---|
| gpt-4o-mini | $0.15 | $0.60 | Chatbots, support |
| gpt-4o | $2.50 | $10.00 | Complex tasks |
| o1-mini | $1.10 | $4.40 | Logic, code |
Common API Errors
OpenAI API error codes are standard HTTP codes, but the causes behind them are not always obvious from the response text.
401 — Incorrect API Key Provided
{"error": {"message": "Incorrect API key provided: sk-***", "type": "invalid_request_error"}} The key failed validation: it was revoked, copied incompletely, or belongs to a different project within the organization. Check the key on the API keys page at platform.openai.com — revoked keys are clearly marked there.
429 — Rate Limit Reached / insufficient_quota
Error 429 actually covers two different problems: exceeding the requests-per-minute limit (temporary, retry with a delay) and running out of paid balance (insufficient_quota, requires topping up). The type field in the JSON response distinguishes between the two cases — they should not be handled with the same retry logic.
Main Error Codes and How to React
| Code | Error type | What to do |
|---|---|---|
| 401 | invalid_request_error / bad key | Check and reissue the key |
| 429 | rate_limit_exceeded | Retry with exponential backoff |
| 429 | insufficient_quota | Top up the balance, retrying will not help |
| 500/503 | server_error | Retry later, the problem is on OpenAI's side |
When a Direct OpenAI API Call Is Not a Good Fit
- User data cannot leave your own infrastructure — in that case a local option such as Ollama is needed.
- You need independence from a single provider — it is worth building in an abstraction layer from the start, as described in the article comparing AI APIs.
- The budget is unpredictable under peak load — without a hard limit on max_tokens and cost monitoring, the bill can grow faster than expected.
- You need a guaranteed response time — the public API offers no latency SLA, and under peak load OpenAI's response can take noticeably longer than usual.
Verifying the Integration Works
curl -s https://api.openai.com/v1/models -H "Authorization: Bearer $OPENAI_API_KEY" | head -c 200 If the key works, the request returns JSON with the list of available models. A 401 error at this step means the problem is with the key, before you even start debugging the chat request logic itself — this narrows down which part of the system is failing much faster.
When designing the integration, build in cost logging from the start: the usage field in the API response contains the exact number of input and output tokens used. Storing these values alongside the request identifier lets you quickly find which usage scenario spiked the bill, instead of investigating after the fact from the total amount in the OpenAI dashboard.