Skip to content

Connect to OpenAI from Python

This guide shows the minimal production-appropriate setup for calling OpenAI from Python:

  • install the SDK
  • store the API key safely
  • make a first request
  • keep the example easy to adapt
Terminal window
python -m pip install openai python-dotenv

Set the key as an environment variable.

Terminal window
$env:OPENAI_API_KEY="your-api-key-here"
Terminal window
export OPENAI_API_KEY="your-api-key-here"

You can also store it in a local .env file for development:

OPENAI_API_KEY=your-api-key-here
from openai import OpenAI
client = OpenAI()
response = client.responses.create(
model="gpt-5.2",
input="Explain retrieval-augmented generation in two short sentences."
)
print(response.output_text)

The current OpenAI docs position the Responses API as the main path for new text-generation work. If you are copying older tutorials, you may still see chat-completions examples. Those older examples are useful historical context, but this page is intentionally using the newer API shape.

import os
from dotenv import load_dotenv
from openai import OpenAI
load_dotenv()
client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
  • hardcoding the key in source files
  • using the wrong environment variable name
  • assuming older SDK examples still reflect the preferred API shape
  • coupling your app too tightly to one specific model name
  • keep the API key in the environment, not in code
  • move model names into config once the app grows
  • start with one small test script before integrating into a larger app