Artificial Intelligence

How to Use the OpenAI API: Models, API Keys and Your First Integration

Talha Aslan 18 min read 2 views

How do you use the OpenAI API?

The OpenAI API is a paid developer interface that lets your own software call OpenAI models over HTTP. To use it, you create a platform account, generate an API key, add prepaid credit, and send requests to the Responses API endpoint through an official SDK or plain HTTP.

In this guide I cover the first integration end to end: account, key, model choice, first request, cost, errors and security. However, I skip the theory of large language models; the focus is getting a first working connection into a website or business process.

Here is what I see in the integrations my team and I build: the code usually takes about an hour. The real time goes into key security, cost control and failure scenarios. So those topics get their own sections here.

What is the difference between ChatGPT and the OpenAI API?

First, many people treat the two as the same thing. ChatGPT is the chat app OpenAI offers to end users. The OpenAI API, on the other hand, is the interface developers use to plug the same model families into their own products.

As a result, billing is separate too. A ChatGPT Plus or Pro subscription does not cover API usage. On the API side you pay for what you use, and the token count sets the price.

TopicChatGPTOpenAI API
Who is it for?End usersDevelopers and businesses
InterfaceWeb, desktop and mobile appsHTTP requests and SDKs
PricingMonthly subscriptionPay as you go, per token
CustomizationLimited (settings, GPTs)Full control: instructions, output format, tools
Data flowUser conversationsData from your own systems

In short, ChatGPT is a product, and the OpenAI API is the door to the models underneath it. If you want an assistant on your site, automatic tagging or content drafts, the API is what you need.

How do you set up an OpenAI API account and billing?

The first step is signing up on the OpenAI platform. You can log in with your ChatGPT account; still, the API side runs on its own organization and project structure.

  1. Log in to the platform and name your organization.
  2. Add a payment method in the billing section and buy prepaid credit.
  3. Create a separate project for each application, for example "website assistant" and "internal reporting".
  4. Set a spending limit and an alert threshold per project.
  5. Invite teammates to the project with the roles they need.

Splitting projects may look like overkill at first. However, tracking the cost and keys of two applications separately lets you answer "where did this bill come from?" in seconds later on.

Some advanced models may require organization verification. So if a model you expect does not show up, check your organization settings first.

How do you create and store an OpenAI API key?

You create the key on the API keys page of the relevant project. The platform shows the full key only once, so copy it to a safe place right away.

The official quickstart recommends keeping the key in an environment variable called OPENAI_API_KEY. Official SDKs read that variable automatically, which means you never need to write the key into your code.

  • Never put the key in source code, a Git repository or front end (browser) code.
  • Use environment variables or a secrets manager on the server; keep your .env file out of the repository.
  • Use separate keys for development and production.
  • If you suspect a leak, revoke the key immediately and create a new one.

Next, the browser side deserves special attention. If you call the API directly from front end JavaScript, anyone who opens the page source can read your key and send requests on your account. The right architecture sends requests from your own server and passes only the result to the browser.

Which OpenAI model should you choose?

Above all, model choice drives both quality and cost. As of September 2026, the official models page suggests three general purpose options in the GPT-6 family: GPT-6 Astra for complex reasoning and coding, GPT-6 Sol to balance intelligence and cost, and GPT-6 Luna for cost sensitive, high volume workloads.

Beyond these, OpenAI offers specialist models for image generation, realtime voice, speech to text and text to speech. Model names change often, so check the current list before you start an integration.

NeedSuggested directionWhy?
Classification, tagging, short summariesCost focused small model (e.g. Luna)High volume, simple task
Customer support assistantBalanced model (e.g. Sol)Quality and speed balance
Code generation, multi step analysisStrongest model (e.g. Astra)Deep reasoning
Image generationImage modelText models do not create images
Voice and live conversationRealtime and audio modelsLow latency matters

My advice: start with the cheapest model that fits and move up only when measured quality demands it. If you do it the other way round, you start with needless cost and it takes a while to notice.

You can also mix models in one application. For example, a small model can triage incoming requests and route only the complex ones to a stronger model.

What is the Responses API and why start with it?

The Responses API is the current interface OpenAI recommends for text generation. The official docs state that models are available through the Responses API and the client SDKs, and the quickstart examples use this endpoint.

Specifically, the endpoint is POST https://api.openai.com/v1/responses. In practice, the simplest request sends only two fields: model and input. The output_text field on the response object gives you the generated text directly.

It also brings tool use (web search, file search, function calling), structured output and multi turn conversation handling together in one interface. That way you do not have to move to another endpoint when you add features later.

If you are starting a new project, start with the Responses API. I explain how it differs from the older Chat Completions interface further down.

How do you send your first OpenAI API request in Python?

First install the official library with pip install openai. Then set your environment variable; on macOS and Linux you can run export OPENAI_API_KEY=your_key in the terminal.

The first request in the official quickstart looks like this:

from openai import OpenAI

client = OpenAI()

response = client.responses.create(model="gpt-6-astra", input="Write a one sentence story.")

print(response.output_text)

Here the client reads the key from the environment variable. To switch models, you change only the model name. For instance, for cost sensitive work you can put in a smaller model ID; copy current model IDs from the models page.

If the first request fails, check three things: the key belongs to the right project, the account has credit, and the model name has no typo. Most cases come down to one of these three.

How do you make the first request with JavaScript and curl?

On Node.js, the install command is npm install openai. The request logic matches Python; only the syntax changes.

import OpenAI from "openai";

const client = new OpenAI();

const response = await client.responses.create({ model: "gpt-6-astra", input: "Hello" });

console.log(response.output_text);

However, run this code only on the server side, for example in Node.js, a Next.js API route or a serverless function. Running the same code in the browser exposes your key to everyone.

If you want to test without an SDK, curl is enough: send a POST request to https://api.openai.com/v1/responses with your key in the Authorization: Bearer header and the model and input fields in a JSON body. In languages without an official SDK, such as PHP, the logic stays the same; you build the HTTP request yourself.

You can find every parameter in the OpenAI quickstart.

How should you structure instructions and input?

Once the first request works, the instruction sets the quality. The Responses API lets you send developer instructions in a separate field, so your rules and the user input never get mixed up.

  • Role and context: say who the model is and whom it serves.
  • Rules: give clear limits on length, tone and bans, for example never inventing prices.
  • Output format: state plainly whether you want plain text, a bullet list or JSON.
  • Example: add a short input and output example when needed.

Also keep user text apart from the instruction. For example, if you paste a question from your website form straight into the instruction, a malicious user can try phrases like "ignore previous instructions". This is prompt injection; you cannot remove the risk entirely, but role separation reduces it.

Also keep the instruction short. A long instruction that goes out with every request shows up on your bill as input tokens.

How do you get structured JSON output?

For website or database integrations, however, free text rarely helps. Your program needs fixed fields it can read.

With structured outputs, the OpenAI API can hold the model response to a JSON schema you define. The schema lists field names, types and required fields. You can find the details in the structured outputs guide.

For instance, you can define "sentiment", "topic" and "summary" fields for a customer review. If you allow only "positive", "negative" and "neutral" in the sentiment field, the model cannot return any other word.

  1. Keep the schema as simple as possible and avoid needless nesting.
  2. List allowed values as enums.
  3. Validate the response in your own code anyway; never trust external data blindly.

As a result, model output turns into clean data you can pass straight to a database or interface.

What is the difference between Chat Completions and the Responses API?

In fact, most older examples online use the Chat Completions interface. It is an earlier structure where you send messages as a role based list.

The Responses API extends that structure. Tool use, server side conversation state and different output types come together in one interface. OpenAI recommends the Responses API for new projects.

FeatureChat CompletionsResponses API
Input structureMessage list (system, user, assistant)Single input or message list, separate instructions field
Text outputInside the choices arrayDirectly through output_text
Built in toolsLimitedTools such as web and file search
Recommended forExisting older projectsNew projects

If an older integration runs fine, you do not have to migrate today. That said, if you plan new features, planning the move early saves you from maintaining two structures side by side.

How do you calculate OpenAI API costs?

OpenAI API pricing works per token. In other words, tokens are the chunks a model uses to process text; roughly, one word equals one or more tokens, and languages with rich word forms, such as Turkish or German, often need more tokens than English.

Three things drive your bill: input tokens you send, output tokens the model returns, and the unit price of the model you pick. Check current prices on the official pricing page, because prices move with model updates.

  • Shorten the instruction and avoid sending needless context with each request.
  • Cap output length with the max tokens parameter.
  • Use a small model for simple tasks.
  • For bulk jobs without urgency, consider the Batch option.
  • If you resend the same fixed instruction many times, look into setups that benefit from prompt caching.

My practical method: send 50 requests with real data, read the total cost in the usage dashboard, and work out the average per request. Multiply that by your expected monthly volume and your estimate becomes realistic.

How do rate limits and usage tiers work?

OpenAI applies per minute request and token limits to each organization. These limits depend on usage tiers that rise with your spending history. A new account starts on a low tier and moves up as payments and time accumulate.

This matters most on launch day, because traffic spikes then. For example, if you try to serve thousands of users from a brand new account, you will hit rate limit errors quickly.

You can see current tiers and limits in the rate limits guide and on the limits page of your account. Compare expected traffic against these numbers before going live.

Also set limits inside your own application. Stopping a single user from firing hundreds of requests per minute protects both your costs and everyone else's experience.

Keep in mind that limits can differ by model. Traffic that runs smoothly on a small model may hit the ceiling once you switch to a larger one, so recheck the limits and rerun a load test after any model change.

What are the common error codes and how do you handle them?

First of all, every API integration runs into errors. A good one turns them into a clear message instead of an ugly screen.

CodeMeaningWhat to do
401Authentication errorCheck the key and project
403Access deniedCheck region, model access and permissions
429Rate limit or quota exceededWait and retry, check your balance
500Server side errorRetry after a short wait
503OverloadedRetry with growing intervals

For retries, use exponential backoff: wait briefly on the first retry, then longer each time, and cap the number of attempts. The official SDKs retry some errors automatically; still, define your own timeout and retry limit.

Finally, log every error. Seeing which endpoint, model and time an error came from tells you quickly whether the problem sits on your side or with the service.

How do you build a secure architecture around the OpenAI API?

In practice, security means more than hiding the key. User input, model output and cost all count as security topics.

  1. Server proxy layer: the browser talks only to your server; your server calls the OpenAI API.
  2. Identity and limits: enforce per user request limits and session checks.
  3. Input hygiene: cap length and strip personal data you do not need.
  4. Output handling: escape model output before rendering it as HTML.
  5. Monitoring: set up spending alerts and unusual traffic warnings.

Teams skip output handling surprisingly often. A model can produce HTML or links inside a response; if you print that straight onto the page, you open a security hole. Therefore, treat model output as untrusted, just like user input.

When you review the wider technical setup of your site, the checklist in my article on technical SEO after AI may help too.

What does OpenAI do with the data you send?

Specifically, this is the question businesses ask most. OpenAI states on its enterprise privacy page that it does not use data sent through the API to train its models by default. It also explains that it may keep data for a limited period to monitor abuse.

That still does not remove your GDPR responsibilities. If you send personal data, you need to disclose it in your privacy notice, assess international transfer rules and sign a data processing agreement where required.

  • Do not send personal data the model does not truly need.
  • Replace identifiers with pseudonyms where possible.
  • In sensitive areas such as health or finance, decide together with your legal advisor.

In short, the safest data is data you never send. Most tagging and summary tasks do not need a person's name or phone number.

How do you manage conversation history and context?

A support assistant has to remember earlier messages. However, the API treats every request independently unless you do something about it.

There are two ways. First, you add earlier messages to the input yourself on every request. Second, you use the Responses API option that continues a conversation by referring to the previous response ID. Your data retention policy decides which one fits.

  • Do not send unlimited history; every old message adds input tokens to the bill.
  • Past a certain length, compress old messages into a short summary.
  • Write down your rule for deleting or keeping history when a session ends.

Put simply, context raises quality but also raises cost. So manage it on purpose.

How do you ground an assistant in your own content?

By default, a general model does not know your products, pricing policy or return terms. If you do not give it that information, it guesses and may produce wrong answers.

The simplest method adds the relevant text to the request as context. For example, you place the matching part of your FAQ page next to the instruction. For larger content sets, the file search tool of the OpenAI API or vector search solutions come into play.

Whichever route you take, remember two rules. First, tell the model to say it does not know when the answer is not in the context. Second, keep your source content current; an old price list means the assistant quotes old prices too.

That way your assistant becomes a helper loyal to your content instead of a creative guesser.

Why does streaming the response matter?

Consider the user side first: waiting for a long answer to finish means several seconds of blank screen for the user. In chat interfaces especially, that pause makes a site feel slow or broken.

The OpenAI API offers a streaming option that sends the answer in pieces. The text appears on screen as the model writes, and the user sees the first words right away. Even if total time stays the same, perceived speed improves clearly.

  • Switch on streaming for chat assistants and long text interfaces.
  • Background batch jobs do not need streaming; waiting for the full answer is simpler.
  • If the connection drops mid stream, offer the user a retry.

In short, streaming is a small extra on the code side and a big difference in user experience. However, the layer between your server and the browser must support it too, so plan the architecture for it from the start.

Which website tasks suit the OpenAI API?

Once the technical setup works, the real question is what to use it for. These are the use cases where I see the most value in practice:

  • On site assistant: a support assistant that answers common questions from your own content.
  • Form and request summaries: summarize contact form messages and route them to the right team.
  • Content drafts: editor reviewed drafts for product descriptions or meta descriptions.
  • Search and tagging: automatic labels for reviews, requests or products.

I cover the user experience side of these use cases in my article on using AI on your website. If you prefer automation without code, AI in web design and automation is a good starting point.

My advice is to start with one clear use case and measure it. Adding five features at once makes it hard to see which one actually works.

How should you treat generated content from an SEO point of view?

In practice, generating content with the OpenAI API is easy; generating good content is another matter. Search engines care less about how you produced a page and more about whether it truly helps users.

Hundreds of similar auto generated pages can drag down how search engines judge your whole site. So treat model output as a draft, then add expert review, original insight and real experience.

Before publishing, you can check keyword usage with the keyword density tool and create structured data with the schema generator. To guide how AI search engines read your site, the llms.txt generator helps as well.

If you want to know how AI driven search changes content strategy, read my guide on writing content for AI Overviews.

What should you check before going live?

Before your first integration goes live, tick off the list below one by one. It summarizes the launch meetings my team and I run.

  1. Does the key live only in a server environment variable, with no trace in the repository?
  2. Are project spending limits and alerts in place?
  3. Does the per user request limit work?
  4. Do users see a clear message for 401, 429 and 500 errors?
  5. Does model output go through escaping before it reaches the page?
  6. Does your privacy notice explain AI processing?
  7. Did you run a quality test with at least 50 realistic examples?

Also, each item on this list comes from a real problem in a project. Spending limits and per user caps in particular stop a small bug from turning into a big bill.

After launch, review the usage dashboard and error logs daily during the first week. That way you catch unexpected behavior early.

What are the most common first integration mistakes?

Across the projects I advise on, the same mistakes keep coming back:

  • Assuming a ChatGPT subscription covers API usage.
  • Putting the API key in front end code or a public repository.
  • Copying old examples from the web with outdated model names.
  • Going live without a spending limit.
  • Writing model output to the database without validation.
  • Trying to run every task on one large model.

Above all, outdated examples cause a lot of trouble. Model names and recommended interfaces change fast. So whenever you copy code from a blog post or forum, compare the model ID and endpoint with the official docs.

The same rule applies to this article: the model names here rely on the official page as of September 2026. Check the current list again when you read it.

When should you get professional help with an OpenAI API integration?

For a quick test or an internal tool, most developers can follow this guide on their own. However, once the integration touches customers, processes personal data or affects your search visibility, strategy matters as much as code.

In projects my team and I run, we handle the integration together with web design and SEO consulting. That way the assistant or content tool does not just work; it also serves the goals of the site.

How your brand appears in AI search engines is part of the same picture. My article on how your brand shows up in ChatGPT and Gemini covers that side.

To sum up, a well built OpenAI API integration gives a small team a lot of extra capacity. A careless one quietly produces cost and risk. The difference comes from thinking about security, measurement and quality control from day one.

Frequently Asked Questions

Is the OpenAI API free?
No. The OpenAI API works on a pay as you go basis. The number of tokens you send and receive, together with the unit price of your chosen model, sets the cost. You need to add prepaid credit to your account. Tests with a small model usually cost little, but I still recommend setting a per project spending limit first.
Does my ChatGPT Plus subscription cover OpenAI API usage?
No, it does not. The ChatGPT subscription covers only the chat app. The OpenAI API has separate billing through the platform account and needs its own balance. You can use the same email for both, but payments and usage tracking stay independent. Not knowing this is the most common confusion during a first setup.
Which programming language should I use for the OpenAI API?
OpenAI offers official SDKs for Python and JavaScript and uses these languages in its quickstart. Because the API runs over HTTP, though, you can send requests from any language, including PHP, Go or Java. Picking the server language your team already uses is usually the best choice for long term maintenance.
Can I use my API key in the browser?
You should not. Anyone who inspects the page source can read a key in browser code and send requests on your account. The right approach sends requests from your own server and passes only the result to the browser. Keep the key in a server environment variable and replace it at once if you suspect a leak.
Does OpenAI train its models on the data I send?
OpenAI states on its enterprise privacy page that it does not use data sent through the API for model training by default. It may, however, keep data for a limited time to monitor abuse. If you send personal data, you still need to review your GDPR notice and international transfer obligations separately.
I keep getting a 429 error. What should I do?
A 429 error means you exceeded a rate limit or your quota. First check whether your account still has credit. If it does, retry with exponential backoff, which means waiting a little longer after each attempt. If the problem continues, review the limits of your usage tier and add a per user request cap in your app.
  • OpenAI API
  • Responses API
  • API Key
  • AI Integration
  • Python
  • JavaScript
  • GPT
Share:
Talha Aslan

Google Partner digital marketing expert. Hands-on with SEO, Google Ads, web design and e-commerce projects since 2012; every post here comes from that experience.

Next project

Let's talk about your project.

Your brief goes straight to Talha Aslan and team: strategy led by Talha, delivery by an experienced team. The first consultation is free; we listen and come back with a clear roadmap.