Skip to main content
This quickstart guide will help you make your first API call using the OpenAI Python SDK. We’ll cover both the Responses API (recommended) and the Chat Completions API.

Prerequisites

Before you begin, make sure you have:
1

Installed the SDK

See the Installation guide for more details.
2

Set up your API key

Get your API key from the OpenAI dashboard.

Using the Responses API

The Responses API is the primary way to interact with OpenAI models. It provides a simplified interface for generating text.

Basic Text Generation

Create your first response:
The api_key parameter is optional. If not provided, the client automatically reads from the OPENAI_API_KEY environment variable.

Simple Input

For straightforward queries, you can pass just the input text:

Vision Input

Process images alongside text:

Using the Chat Completions API

The Chat Completions API is the previous standard for generating text, and is supported indefinitely.

Basic Chat Completion

Message Roles

The Chat Completions API uses different message roles:
  • developer: System-level instructions for the model’s behavior
  • user: User messages in the conversation
  • assistant: Previous assistant responses (for conversation history)

Streaming Responses

Stream responses in real-time for a better user experience:

Async Usage

For async applications, use AsyncOpenAI instead of OpenAI:
The async client provides identical functionality to the sync client, but all methods use await.

Error Handling

Handle API errors gracefully:

Error Types

The SDK provides specific exception types for different errors:

Common Configuration

Timeouts

Set custom timeout values:

Retries

Configure retry behavior:
Certain errors (connection errors, 408, 409, 429, and ≥500) are automatically retried with exponential backoff.

Custom Base URL

Use a custom API endpoint:

Next Steps

Now that you’ve made your first API call, explore more advanced features:

Responses API

Learn more about the Responses API

Chat Completions

Explore the Chat Completions API

Streaming

Master streaming responses

Error Handling

Handle errors like a pro