ChatGPT API: How to Set Up, Pricing, and Code Examples (2026)
MarkdownA practical guide to setting up the ChatGPT API, comparing models and pricing, and building applications with code examples.
The ChatGPT API gives developers programmatic access to OpenAI models. This guide covers API key setup, model selection, pricing, code examples, and practices for building applications and managing costs.
What Is the ChatGPT API?
The ChatGPT API lets developers integrate AI capabilities into applications through HTTP requests. Applications send structured requests to OpenAI and receive JSON responses containing model output.
How the ChatGPT API Works
The process follows four steps:
You send a request. Your application sends a POST request to OpenAI with a JSON payload containing a model name, messages, and parameters such as temperature and token limits.
OpenAI processes the request. The model generates a response and returns it in a JSON object. With streaming enabled, tokens arrive incrementally.
Your application receives the response. The response includes generated content, token usage, model information, and a request ID.
Billing occurs. Charges depend on processed tokens. Input and output tokens may have different rates.
Prompt length, model selection, and caching affect performance and cost.
ChatGPT API Models and Pricing (2026)
Model availability, features, and prices can change. Check OpenAI’s API pricing and developer documentation for current details. Pricing is generally based on input and output tokens, which may have different rates.
Models and Capabilities
The source lists GPT-5.4, GPT-5.4 mini, GPT-5.4 nano, GPT-5.4 pro, GPT-5.2, GPT-5 mini, GPT-5 nano, GPT-4.1, GPT-4.1 mini, GPT-4.1 nano, o3, o4-mini, and o3-mini. Its specific claims about launch dates, prices, context windows, model availability, and capabilities are time-sensitive and should be checked against current official documentation before use.
How to Choose a Model
Choose a model based on your task, quality requirements, latency, and budget. Test candidates on representative workloads and compare output quality and cost.
- Customer support, Q&A, and content generation: compare models on representative requests.
- Code generation, analysis, and agent workflows: evaluate quality on your own tasks.
- Image understanding and multimodal applications: confirm the model’s supported inputs.
- Math and multi-step reasoning: test reasoning models against your requirements.
- Classification and extraction: consider throughput and cost alongside accuracy.
How to Set Up the ChatGPT API
You need an API key to authenticate requests. Treat it as a secret and store it securely.
How to Obtain an OpenAI API Key
Step 1: Access the OpenAI Platform
- Visit platform.openai.com/api-keys and sign in or create an account.
Step 2: Create Your API Key
- Open API Keys in the dashboard.
- Select Create new secret key and optionally give it a project-specific name.
- Copy the key when it is displayed; it may not be shown again.
Step 3: Store It Securely
- Store the key in a password manager or environment variable.
- Never commit API keys to version control or expose them in client-side code.
- If you use a
.envfile, add it to.gitignoreand keep the file out of version control.
Security notes:
- A key can grant access associated with your account and billing.
- If a key is lost, create a replacement.
- Revoke keys that may have been compromised.
- Use separate, appropriately scoped keys for different projects when available.
Setting Up Your Development Environment
The API can be used from any programming language that can make HTTP requests. Python, JavaScript, and Java are common choices.
1. Python: Simplicity and a Rich Ecosystem
Python’s syntax and library ecosystem make it a common choice. OpenAI’s Python package can simplify authentication, request formatting, and error handling. Packages such as python-dotenv can help manage environment variables.
Python is also used in machine learning, data science, web development, and automation, making it useful for projects that combine API calls with data processing.
2. JavaScript: Flexibility for Web Applications
JavaScript works for backend applications with Node.js and for web applications using frameworks such as React, Vue, or Next.js. Its asynchronous features, including async/await and Promises, support non-blocking API requests.
3. Java: Scalability and Performance
Java is commonly used for enterprise applications. Static typing can catch some errors at compile time, and its concurrency features can help applications handle multiple requests. It can suit software that integrates with existing Java systems.
The examples below use Python. If you use JavaScript or Java, adapt the syntax to your language and SDK.
Best Practices for Using the ChatGPT API
1. Write Clear and Specific Prompts
Clear, specific instructions can improve the usefulness of responses.
- Specify the desired format, tone, and length.
- Provide examples when useful.
- Use developer instructions to set behavior and context.
- Break complex tasks into smaller steps.
Example:
prompt.py
1# Bad prompt2response = client.chat.completions.create(3 model="gpt-4.1", messages=[{"role": "user", "content": "Write about marketing"}]4)5
6# Good prompt7response = client.chat.completions.create(8 model="gpt-4.1",9 messages=[10 {11 "role": "system",12 "content": "You are a digital marketing expert who writes concise, actionable advice.",13 },14 {15 "role": "user",16 "content": "Write a 3-paragraph email marketing strategy for a SaaS startup targeting small businesses. Focus on deliverability, segmentation, and automation.",17 },18 ],19)
2. Use Structured Outputs for Reliable Data
For JSON or other structured data, use the API’s structured output features instead of parsing free-form text. Check the documentation for the supported format and constraints.
prompt.py
1response = client.chat.completions.create(2 model="gpt-4.1",3 messages=[4 {5 "role": "user",6 "content": "Extract the product name, price, and category from: 'The new iPhone 15 Pro costs $999 and is in the smartphones category'",7 }8 ],9 response_format={10 "type": "json_schema",11 "json_schema": {12 "name": "product_extraction",13 "schema": {14 "type": "object",15 "properties": {16 "product_name": {"type": "string"},17 "price": {"type": "number"},18 "category": {"type": "string"},19 },20 "required": ["product_name", "price", "category"],21 },22 },23 },24)25
3. Implement Streaming for Better User Experience
Streaming can show response content as it arrives rather than waiting for the complete response.
prompt.py
1stream = client.chat.completions.create(2 model="gpt-4.1-mini",3 messages=[{"role": "user", "content": "Explain quantum computing in simple terms"}],4 stream=True,5)6
7for chunk in stream:8 if chunk.choices[0].delta.content:9 print(chunk.choices[0].delta.content, end="")
4. Manage Context and Token Limits
A model’s context window limits the tokens available for input and output. Monitor usage to avoid truncation and unexpected costs.
- Keep conversation history concise; summarize or trim older messages.
- Use the appropriate output limit supported by the model and API.
- Check response usage information.
- Consider chunking or summarizing long documents.
prompt.py
1response = client.chat.completions.create( model="gpt-4.1-mini", messages=messages, max_tokens=500 # Limit response length )2
3# Track usage print(f"Tokens used: {response.usage.total_tokens}")
5. Handle Errors Gracefully
Requests may fail because of network issues, rate limits, invalid input, or service outages. Handle errors according to the SDK and API documentation.
prompt.py
1from openai import OpenAI, APIError, RateLimitError, APIConnectionError2import time3
4
5def make_api_call_with_retry(client, messages, max_retries=3):6 for attempt in range(max_retries):7 try:8 response = client.chat.completions.create(9 model="gpt-4.1-mini", messages=messages10 )11 return response12
13 except RateLimitError:14 # Exponential backoff15 wait_time = (2**attempt) + 116 print(f"Rate limit hit. Retrying in {wait_time} seconds...")17 time.sleep(wait_time)18
19 except APIConnectionError:20 print(f"Connection error. Retrying... (Attempt {attempt + 1})")21 time.sleep(2)22
23 except APIError as e:24 print(f"API error: {e}")25 return None26
27 print("Max retries exceeded")28 return None
6. Optimize Costs
- Choose a model suited to the task and compare quality and cost.
- Set an output limit to avoid unnecessarily long responses.
- Cache results for repeated queries where appropriate.
- Batch similar requests when supported and suitable.
- Monitor spending in the OpenAI usage dashboard.
prompt.py
1# Cost-effective approach2response = client.chat.completions.create(3 model="gpt-4.1-mini", # Cheaper model for simple tasks4 messages=[{"role": "user", "content": prompt}],5 max_tokens=150, # Limit response length6 temperature=0.3, # Lower temperature for more deterministic, cheaper outputs7)8
Consult the OpenAI pricing page for current model prices.
7. Implement Rate Limiting
Rate limits may apply to requests and tokens over time, depending on account and service conditions. A 429 response indicates a rate-limit condition.
- Use backoff when appropriate.
- Track request rates and throttle if needed.
- Check your account’s current limits and eligibility for changes.
- Consider batch processing for suitable workloads.
8. Use Function Calling for Tool Integration
Function calling allows a model to request that your application call a function or tool. Your application handles the call and returns results as appropriate.
prompt.py
1tools = [2 {3 "type": "function",4 "function": {5 "name": "get_weather",6 "description": "Get current weather for a location",7 "parameters": {8 "type": "object",9 "properties": {10 "location": {"type": "string", "description": "City name"}11 },12 "required": ["location"],13 },14 },15 }16]17
18response = client.chat.completions.create(19 model="gpt-4.1",20 messages=[{"role": "user", "content": "What's the weather in San Francisco?"}],21 tools=tools,22)23
24# Check if model wants to call a function25if response.choices[0].message.tool_calls:26 # Execute your function and return results to the model27 pass
9. Secure Your API Key
- Never commit keys to version control.
- Keep keys in environment variables or another secure store.
- Rotate keys when needed and revoke old or exposed keys.
- Use separate keys per project where available.
- Monitor usage for unexpected activity.
- Restrict key permissions where supported.
10. Test with Different Models
Compare models on representative workloads for quality, latency, and cost. Start with a model that meets your requirements and move to another if testing shows a need.
Rate Limits and Access Tiers
Limits and account tiers can change. Check the OpenAI usage dashboard and current documentation for account-specific limits, spending controls, and rate-limit details. When a request is rate-limited, follow the API’s guidance and use an appropriate backoff strategy.
App Ideas to Build with the ChatGPT API
1. Customer Support Chatbots
Build assistants that answer FAQs, track orders, troubleshoot issues, and provide customer support. Function calling can connect an application to CRM, ticketing, or order-management systems.
2. Virtual Assistants for Productivity
Build assistants that manage schedules, draft emails, organize tasks, summarize documents, and extract action items from meeting notes using productivity APIs.
3. AI-Powered Educational Tools
Create language-learning applications, interactive tutors, coding mentors, and study tools that generate practice questions and adapt to a learner’s needs.
4. Content Creation Tools
Build tools for drafting blog posts, social media content, email campaigns, product descriptions, and video scripts. Review generated content for accuracy and fit before publishing.
5. Data Analysis and Insights
Let users query databases in natural language, generate reports, identify trends, and create explanations of data. Validate outputs against the underlying data.
6. Code Generation and Debugging
Build code-generation, documentation, bug-finding, refactoring, or test-writing tools. Review generated code before using it.
7. Knowledge Bases and Intelligent Search
Create internal knowledge bases with conversational search, research assistants, and tools that summarize documents. Retrieval-augmented generation can connect a model to domain-specific material. Protect sensitive information and verify generated answers against source documents.
Frequently Asked Questions
Does ChatGPT have an API?
Yes. OpenAI provides an API for programmatic access to models. Applications can make HTTP requests or use official SDKs; check current documentation for available models and features.
How much does the ChatGPT API cost?
Pricing depends on the model and usage. Check the OpenAI pricing page for current rates and available cost-management options.
What is the difference between ChatGPT and the ChatGPT API?
ChatGPT is a conversational product. The API lets developers send requests programmatically and integrate model responses into applications, with controls determined by the API and selected model.
What is the newest model available in the ChatGPT API?
Model availability changes. Consult OpenAI’s current API documentation for the latest models and capabilities.
Should I use the Responses API or Chat Completions?
Choose an API based on your application and the features it needs. OpenAI’s documentation describes current endpoints and migration guidance. Existing applications should follow the documented support and migration instructions for their endpoint.
Can I use the ChatGPT API for free?
Costs and any credits depend on current account terms and usage. Check OpenAI’s pricing information before planning a budget.
Build with the ChatGPT API
Start with a proof of concept focused on one specific problem. Evaluate the result, cost, and reliability on representative inputs, then expand as needed.
Essential resources:
ChatGPT API: How to Set Up, Pricing, and Code Examples (2026)
Discover an API key issued by Ailoot. One Ailoot-issued API key gives you 1,284 models and variants across 15 categories. That catalogue puts Ailoot among the world’s largest AI routers by model count. Build with Claude, DeepSeek or Kimi alongside FLUX for images, Kling for video, Eleven v4 for speech, Lyria for music and Tripo3D for 3D. Ailoot also supports semantic search and structured decisions.
Create an Ailoot-issued key for your “chat gpt api key” project and use GPT-6.2 Astra or GPT-6.2 Sol through the Ailoot API. One balance also covers Claude, Gemini and media models.
Bring your “chatgpt api key” and “chatgpt api keys” projects to Ailoot alongside your other model workflows. Set limits on project keys in your Ailoot account. Ailoot workspaces give colleagues controlled access while the company manages spending centrally.
Use new flagship models from day one on the same Ailoot balance. One subscription covers the full catalogue. Subscriptions and promo codes can bring model costs down by up to 50% compared with official provider API prices. Open your account at https://ailoot.ai/ or request a code from the team.