Modified

The OpenAI API in Swedish

The OpenAI API lets your own programs use OpenAI's models. Instead of you typing in ChatGPT, your program sends a question to OpenAI's servers and gets an answer back. You pay for what you use, separately from a ChatGPT subscription. The guide goes from what an API is to your first request in Python, JavaScript or curl.

  1. Create an accountat platform.openai.com
  2. Create an API keyunder API keys in your account
  3. Store the keyin the OPENAI_API_KEY environment variable
  4. Install the SDKfor Python or JavaScript
  5. Send the first requestto the Responses API
Five steps from account to the first answer from the OpenAI API.

Basics

What is an API and an API key?

An API is a way for programs to talk to each other. A website has pages for people. An API has an address for programs. The program sends a request in a set format and gets an answer in a set format, usually JSON. JSON is a text format with named fields that programs read easily.

An API key is a secret code that shows who sends the request. Through the key, OpenAI links every request to your account and charges for it. Anyone who has your key can use your account, so treat it like a password.

How an API request travels

Your programan app, a script, a web page$OPENAI_API_KEY
The question and the keythe key shows who pays
The answer as dataand how many tokens it used
The company's serverapi.openai.comGPT
Tokens inwhat you send
Tokens outwhat the model writes, costs more
You pay for tokens in both directions. The key stays in the environment variable, never in the code.

Are ChatGPT Plus and the OpenAI API the same thing?

ChatGPT Plus and the OpenAI API are two different things, and OpenAI itself states that API prices are separate from the subscription. A ChatGPT subscription gives you ChatGPT and Codex with built-in limits. You pay for the API per token, a piece of text that is often part of a word, through your account on OpenAI's platform.

If you only need answers and texts, use ChatGPT. If a program you build needs answers from a model, use the API. The program might be a customer service tool, a translator or a script that sorts email.

Who needs the OpenAI API?

The OpenAI API is for developers and for you if you want to learn to build with AI. For the examples you need to be able to run commands in a terminal. You also need Python or Node.js on your computer. Node.js is the program that runs JavaScript outside the browser. If the terminal is new to you, read part 2 on Codex first.

The API can do more than text. OpenAI's models take text and images, and the API has built-in tools for web search, file search and code execution, according to OpenAI's documentation.

Get started

How do you get started with the OpenAI API?

Three steps give you an account and a key your program can use.

1. Create an account on the platform

Go to platform.openai.com and create an account, or sign in with your OpenAI account. Under Billing you add credits, which then pay for your requests.

2. Create an API key

Open the API keys page and create a key for your project. Copy the key and store it somewhere safe. For your own development a project key is enough. For a program that others use, OpenAI recommends a service account, an account for the program instead of a person, with its own key.

3. Store the key in an environment variable

Store the key in the environment variable OPENAI_API_KEY. OpenAI's libraries read the key from there on their own, according to OpenAI's quickstart, so the key never needs to be in the code. Replace your_api_key_here with your key in the command below. On Mac and Linux, export only applies in the terminal window where you typed the command. On Windows, setx saves the variable for new windows, so open a new PowerShell window afterwards.

Store the API key in an environment variable
export OPENAI_API_KEY="your_api_key_here"

Your first request to the OpenAI API

The Responses API is the way into the API that OpenAI recommends for all new projects, according to OpenAI's guide to migrating from the older Chat Completions. Built-in tools such as web search and file search belong to Responses, according to the same guide.

First install OpenAI's SDK for your programming language. An SDK is a ready-made code package that handles the requests for you. Then save the example in a file named example.py or example.mjs and run the file. The Python and JavaScript examples come from OpenAI's quickstart and the curl example from OpenAI's text generation guide. The program curl sends requests from the terminal on Mac and Linux and needs no SDK.

The request sends a model name in the model field and a text in the input field. The model name in the example applies at the time of writing, and OpenAI's models page shows which names apply now. The answer comes back with several fields, and the output_text field holds the text. Replace the text with a question of your own in Swedish and run it again.

Install OpenAI's SDK
pip install openai
First request to the Responses API
from openai import OpenAI

client = OpenAI()

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

print(response.output_text)
Run the example
python example.py

Models and tools

Which models are there, and what does the OpenAI API cost?

You pay per million tokens for the text you send in and, at a higher rate, for the text the model writes. Your question, files you send along and the model's answer are all counted in tokens. A larger model costs more per token than a smaller one, according to OpenAI's pricing page.

OpenAI has models in several sizes, according to OpenAI's models page. The largest suits hard reasoning and code, and OpenAI recommends starting with it. A balanced model weighs capability against cost. A fast model suits images, natural writing and computer use, meaning operating a computer. The smallest suits large volumes where cost matters most.

One example: at the time of writing, the largest model costs 10 dollars per million tokens in and 50 dollars per million tokens out for requests with a short context, meaning little text per request, according to OpenAI's pricing page. The pricing page shows the price for each model.

How do you get the answer as JSON? Structured Outputs

Structured Outputs makes the model always answer according to a JSON schema you define, according to OpenAI's documentation. A JSON schema is a template that says which fields the answer must have. Then no required field goes missing, and the model does not invent values outside the allowed ones. Structured Outputs suits answers that a program will read, for example to pick out names, dates and participants from an email.

In Python you describe the format with a class, a description of the fields in the code. The function responses.parse returns the answer with the fields filled in. OpenAI recommends Structured Outputs over JSON mode, which gives valid JSON but does not follow a schema.

Structured Outputs in Python
Terminal
from openai import OpenAI
from pydantic import BaseModel

client = OpenAI()


class CalendarEvent(BaseModel):
    name: str
    date: str
    participants: list[str]


response = client.responses.parse(
    model="gpt-6-astra",
    input=[
        {"role": "system", "content": "Extract the event information."},
        {
            "role": "user",
            "content": "Alice and Bob are going to a science fair on Friday.",
        },
    ],
    text_format=CalendarEvent,
)

event = response.output_parsed

What is function calling?

Function calling, also called tool calling, lets the model use functions in your program. A function is a piece of code that does one thing, for example fetching the weather or looking up an order. The model never runs the code itself. It says which function it wants to use and with which values. Your program runs the function and sends back the result.

The flow has five steps, according to OpenAI's documentation:

  • Send a request with the tools the model may use.
  • Receive a tool call from the model.
  • Run the code in your program with the values from the call.
  • Send a new request with the result from the tool.
  • Receive the final answer, or more tool calls.

How a tool call travels

  1. Sends the question and the available tools
  2. Replies: run the tool, with these values
  3. Runs the code itself, for example looks up an order
  4. Sends the result back
  5. Writes the answer with the result
The model never runs the code itself. Check the values before your program does something that cannot be undone.

How do you show the answer while it is being written?

Streaming sends the answer piece by piece while the model writes, instead of all at once. The user then sees the text grow, as in ChatGPT. You turn on streaming with stream=True. The answer then arrives as a series of events, small messages your program reads one at a time.

Streaming in Python
Terminal
from openai import OpenAI

client = OpenAI()

stream = client.responses.create(
    model="gpt-6-astra",
    input=[
        {
            "role": "user",
            "content": "Say 'double bubble bath' ten times fast.",
        },
    ],
    stream=True,
)

for event in stream:
    print(event)

Batch API: a lower price for jobs that can wait

The Batch API runs many requests in the background at a lower price. OpenAI's documentation gives a 50 per cent discount, a separate pool of higher limits and results within 24 hours. You collect the requests in a JSONL file, a text file with one request per line. Each line has its own custom_id, a name you choose. Fetch the result when the job is done. Each file may only contain requests to one model, according to the same documentation.

Batch suits jobs that are not urgent, such as classifying thousands of texts, summarising an archive or testing a prompt against many examples.

Limits and safety

Rate limits and usage tiers: how much can you use?

Rate limits cap how much you may send. OpenAI measures among other things requests per minute (RPM) and tokens per minute (TPM), according to OpenAI's rate limits page. The limits apply per organisation and project, not per person, according to the same page.

OpenAI raises the limits automatically as you buy more credits. The levels are called usage tiers, and a higher tier gives higher limits, according to OpenAI's rate limits page. The same page has a free tier for users in allowed countries and shows what each tier requires and which limits apply to each model.

Set a spend limit for the account or the project. OpenAI has two kinds. An alert sends a notification but lets the requests continue. A hard limit stops the requests.

What does OpenAI do with the data you send to the API?

OpenAI does not train its models on data you send to the OpenAI API, unless you choose to share it. That has been the case since 1 March 2023, according to OpenAI's data page. By default OpenAI keeps logs for up to 30 days to detect abuse, according to the same page. Approved customers can get Zero Data Retention or Modified Abuse Monitoring, which keep the content out of those logs.

OpenAI has a European region for the EEA and Switzerland at the address eu.api.openai.com, according to OpenAI's data page. To use the region, you contact OpenAI's sales team, get approved for the abuse monitoring controls and sign an amendment on modified retention, according to the same page. The region covers your content but not system data such as account details and billing. For models released from 5 March 2026, regional processing costs 10 per cent more, according to OpenAI's pricing page.

If you send personal data to the API, GDPR applies. First sign a data processing agreement with OpenAI, a contract on how OpenAI may handle the data.

Data from your users can contain attempts to steer the model, called prompt injection. Never let the model's answer alone decide something that costs money or deletes data. More on risks is in the AI safety guide.

OpenAI API, Claude API or Gemini API?

The OpenAI API, the Claude API and the Gemini API work the same way. You have a key and an address, send text in and get an answer out, and pay per token. The differences lie in the models, the prices and the built-in tools.

Keep the call in one place in your program, so the model can be swapped. Then you can compare price and quality for your own task. The prompt guide shows how to write good instructions for all three.

Common questions about the OpenAI API

Is the OpenAI API free?

The OpenAI API costs per token, according to OpenAI's pricing page. The quickstart calls the first test request free. Then it asks you to add credits to keep building.

Which programming languages can you use?

OpenAI has official libraries for JavaScript and TypeScript, Python, .NET, Java, Go and Ruby, according to OpenAI's quickstart. Other languages can call the API directly over HTTP, the web's way of sending requests, as the curl example shows.

Does old Chat Completions code still work?

Chat Completions is still supported, according to OpenAI's guide to migrating to Responses. Some newer models, however, require the Responses API for tool calling, according to OpenAI's function calling guide.

What does error code 429 mean?

Error code 429 means a limit has been reached, such as a hard spend limit or a temporary rate limit, according to OpenAI's rate limits page. If the error is about a rate limit, wait a moment and try again. Otherwise check the spend limit for the project.

Do you need to know how to program?

The API needs a little code. You can start by letting Codex write the code, while you read along and learn what each line does.

Sources: OpenAI, quickstart · OpenAI, API pricing · OpenAI, models · OpenAI, Responses API · OpenAI, Structured Outputs · OpenAI, Batch API · OpenAI, rate limits · OpenAI, data