Python OpenAI API Tutorial for Beginners

Calling the OpenAI API from Python takes about ten lines once the package and key are in place. Most beginner trouble comes from the setup around them.

Quick answer: run pip install openai python-dotenv, put OPENAI_API_KEY in a .env file, then call client.responses.create() with a model and an input, and print response.output_text.

from dotenv import load_dotenv
from openai import OpenAI

load_dotenv()
client = OpenAI()
response = client.responses.create(model="gpt-6-luna", input="Hi!")
print(response.output_text)

In this tutorial, I’ll walk you through the Python OpenAI API from a clean install to text you can tune: the key, the first call, reading the response, picking a model, and three settings that change what you get back.

I ran each script for real on Python Python 3.12.5, openai 3.61.0 and gpt-6-luna, OpenAI’s most efficient model right now. The screenshots are real VS Code and Command Prompt runs.

What You Need Before Calling the OpenAI API from Python

  • Python 3.10 or newer. The current openai package won’t install on older versions (install a newer Python next to the old one).
  • An OpenAI platform account with API credits. A ChatGPT subscription doesn’t include API usage; billing is separate.
  • An API key from the API keys page of your OpenAI dashboard. Copy it once; you can’t view it again later.
  • VS Code (or any editor) and a terminal.

Our running sample is Harbor Lane Coffee, a made-up coffee shop in Portland, Maine. Every Python script below asks the model to write menu copy, a tagline or a welcome note for it.

Step 1: Install the openai Package in a Python Virtual Environment

A virtual environment keeps the OpenAI packages away from your other Python projects. If venvs are new to you, my Python virtual environments tutorial explains them.

First, a tiny script that proves the install worked. (My Python packages tutorial explains pip itself.) Here’s how to set it up:

  1. Create a folder named openai-demo and open it in VS Code with File > Open Folder.
  2. Create a file named check_setup.py in that folder and paste the code below into it.
  3. Open Command Prompt (or View > Terminal in VS Code) and go to the folder with the cd command.
  4. Type the four commands from the next block, one per line, pressing Enter after each.
import sys

import dotenv              # from the python-dotenv package
import openai

print("Python", sys.version.split()[0])
print("openai", openai.__version__)
print("python-dotenv is installed")

Type these in Command Prompt inside the openai-demo folder. On macOS or Linux, activate with source .venv/bin/activate instead:

python -m venv .venv
.venv\Scripts\activate
pip install -q openai python-dotenv
python check_setup.py
Command Prompt creating a Python virtual environment, installing openai and python-dotenv with pip and printing the openai version
A fresh venv, a quiet pip install and the check script reporting openai 3.61.0.

The -q flag only hides pip’s download list, and the pip upgrade notice is harmless.

Important: install and run from the same activated venv. Mixing them up is the classic cause of ModuleNotFoundError after pip install. Teams often pin the version too, as in pip install a specific version.

Step 2: Store Your OpenAI API Key in a .env File

Never paste your key into a Python file. Code gets shared, pushed to GitHub and pasted into chats, and a leaked key can run up charges fast.

Create a file named .env in the openai-demo folder (VS Code: File > New File). Add one line, with your real key after the equals sign:

OPENAI_API_KEY=sk-...your-key...

If the folder is a Git repo, add .env to your .gitignore file so the key never gets committed:

.env

load_dotenv() copies that line into the process environment, and OpenAI() reads OPENAI_API_KEY from there on its own. My Python environment variables tutorial covers os.environ in more depth.

Step 3: Make Your First Python OpenAI API Call

The Responses API is OpenAI’s recommended API for new projects, so that’s what we use here. One call sends a model name and your input, and you get a response object back.

Save this as first_call.py in the openai-demo folder and run python first_call.py in the VS Code terminal:

from dotenv import load_dotenv
from openai import OpenAI

load_dotenv()               # copies OPENAI_API_KEY from .env
client = OpenAI()           # finds the key on its own

response = client.responses.create(
    model="gpt-6-luna",
    input="Write one sentence for a coffee shop menu about "
          "our Maple Pecan Cold Brew ($5.75).",
)
print(response.output_text)

Output:

Smooth, slow-steeped cold brew with warm maple sweetness and toasted pecan notes — $5.75.
VS Code running a first Python OpenAI API call with client.responses.create and printing output_text
One Responses API call, one sentence of menu copy.

How does this work? OpenAI() builds a client with your key. responses.create() sends the request and waits, and output_text joins every text piece of the reply into one Python string.

Run it twice and you’ll get two different sentences. That’s normal: the model samples words, so text generation isn’t repeatable by default. The same code also runs in a Jupyter notebook cell.

Step 4: Read output_text, usage and status from the Response

The response holds more than text. Same client, a shorter prompt, and a few more print() lines show what comes back.

Save this as read_response.py and run it in the VS Code terminal:

from dotenv import load_dotenv
from openai import OpenAI

load_dotenv()
client = OpenAI()

response = client.responses.create(
    model="gpt-6-luna",
    input="Suggest a name for a fall latte. Name only.",
)
usage = response.usage
print("Text:     ", response.output_text)
print("Model:    ", response.model)
print("Status:   ", response.status)
print("Items:    ", [item.type for item in response.output])
print("Input:    ", usage.input_tokens, "tokens")
print("Output:   ", usage.output_tokens, "tokens")
print("Reasoning:", usage.output_tokens_details.reasoning_tokens,
      "of the output tokens")

Output:

Text:      Maple Ember Latte
Model:     gpt-6-luna
Status:    completed
Items:     ['reasoning', 'message']
Input:     17 tokens
Output:    31 tokens
Reasoning: 21 of the output tokens
VS Code output of a Python OpenAI response object showing output_text, model, status, output items and token usage
This call used 17 input and 31 output tokens, 21 of them reasoning.

How does this work? response.output is a Python list of items. gpt-6-luna is a reasoning model, so a reasoning item comes before the message item that holds the text.

You pay for input and output tokens, and reasoning tokens count as output even though you never see them. Always check status: completed means the reply is whole.

Step 5: Choose an OpenAI Model for Your Python Script

The model name is a plain string, so switching models means changing one word. Which names can your key use? Ask the API: listing models costs nothing, and sorted() puts the IDs in order.

Save this as list_models.py and run it in the VS Code terminal:

from dotenv import load_dotenv
from openai import OpenAI

load_dotenv()
client = OpenAI()

# listing models is free: no tokens are used
names = sorted(m.id for m in client.models.list()
               if m.id.startswith("gpt-6"))
print(len(names), "GPT-6 models on this account:")
for i in range(0, len(names), 3):          # three per line
    print("  ", ", ".join(names[i:i + 3]))

Output:

11 GPT-6 models on this account:
   gpt-6-astra, gpt-6-astra-healthcare, gpt-6-luna
   gpt-6-sol, gpt-6.1-sol, gpt-6.1-sol-healthcare
   gpt-6.1-terra, gpt-6.2-astra, gpt-6.2-astra-healthcare
   gpt-6.2-sol, gpt-6.2-sol-healthcare
VS Code run of a Python script listing the GPT-6 model IDs available to an OpenAI API key
11 GPT-6 model IDs showed up for my key.

Here’s how I’d choose among them for Python text generation:

ModelWhat it’s forWhen I pick it
gpt-6-lunaMost efficient, high-volume tasksLearning, short text, scripts that run often
gpt-6.1-terraFast, natural writing, visual reasoningPolished copy or images in the input
gpt-6.2-solEveryday work and agents at scaleMulti-step tasks and tool calls
gpt-6.2-astraHardest problems, top qualityComplex reasoning where cost matters less

I start every Python project on gpt-6-luna and move up only when the output isn’t good enough. Bigger models cost more per token.

Step 6: Shape Generated Text with Instructions

instructions is the system prompt: the role, tone and rules the model follows for that request. Your input stays the actual task.

Same Maple Pecan Cold Brew request, sent twice: once bare, once with our menu-copy rules.

Save this as instructions_demo.py and run it in the VS Code terminal:

import textwrap

from dotenv import load_dotenv
from openai import OpenAI

load_dotenv()
client = OpenAI()
MODEL = "gpt-6-luna"
ASK = "Describe our Maple Pecan Cold Brew ($5.75)."
STYLE = ("You write menu copy for Harbor Lane Coffee in "
         "Portland, Maine. One sentence, under 20 words, "
         "friendly, no emojis.")

plain = client.res