OpenAI Python SDK: Make Your First API Request

To send an OpenAI API request from Python, a program needs a client that connects to the service. The OpenAI Python SDK is a client library for calling OpenAI APIs from Python.

I’ll walk through setting up the SDK and making a first request with the Responses API.

TL;DR

The OpenAI Python SDK is the official Python client for OpenAI APIs. Install it in your project environment, set an API key outside your source, and start a new text-generation integration with the Responses API.

  • The current official library requires Python 3.10 or later.
  • The official README presents client.responses.create() as the primary model API.
  • Use OPENAI_API_KEY for credentials and keep its value out of source control.

What is the OpenAI Python SDK?

The OpenAI Python SDK is a typed client library for calling OpenAI’s REST API from Python. It gives an application synchronous and asynchronous clients, typed request and response objects, and helpers for HTTP behavior such as retries and timeouts.

The client sends a request to an API endpoint and returns a response object. Your application still chooses a model, handles the result and protects its credentials. API access and usage charges are separate from installing the Python package.

PartRole
OpenAISynchronous client for regular Python code
AsyncOpenAIAwaitable client for async applications
Responses APIGenerate model output and use supported tools
API keyAuthenticate requests

OpenAI’s current Python library README describes the Responses API as the primary way to interact with models. Chat Completions remains documented, so existing integrations can keep using it when that endpoint fits their needs. For new text-generation work, begin with Responses unless a required feature points elsewhere.

How to make your first OpenAI Python SDK request

A first request has four parts: install the package, set a key, create a client and call an endpoint. Use the same Python environment to install and run the application.

Step 1: Install the SDK in a project environment

The official library supports Python 3.10 and later. A virtual environment keeps project packages separate from system Python.

python3 -m venv .venv
. .venv/bin/activate
python -m pip install openai

Use python -m pip so pip belongs to the interpreter activated for the project. Check the installed version with python -m pip show openai.

Step 2: Set the API key outside the source file

Create a key in the OpenAI platform, then set OPENAI_API_KEY in the shell that starts Python. The default client reads this variable automatically.

export OPENAI_API_KEY="your-api-key"

For PowerShell, set the current session with $env:OPENAI_API_KEY=”your-api-key”. Keep the credential out of a committed script and logs. If the variable is missing, client initialization or the request will report an authentication problem.

A small preflight can confirm the variable exists without displaying its value.

I ran this check in the current shell, where the result showed the variable was absent:

import os
print("OPENAI_API_KEY configured:", bool(os.environ.get("OPENAI_API_KEY")))
OPENAI_API_KEY configured: False
Terminal check showing whether the OpenAI API key environment variable is configured

Step 3: Create a client and send a Responses request

Save this as first_response.py. It sends a billable network request, so run it only with a valid key and an account that can use the chosen model.

from openai import OpenAI

client = OpenAI()
response = client.responses.create(
    model="gpt-5.5",
    instructions="Answer in one sentence.",
    input="What does a Python virtual environment isolate?",
)
print(response.output_text)

The model generates the printed sentence, so it is not a fixed program output. The output_text helper gives the combined text without requiring the caller to assemble every text item in the response. Check the current model catalog and account access before selecting a model name.

Step 4: Inspect response items when the app needs them

Use output_text when the application needs a plain answer. Inspect response.output when it needs structured items, such as tool activity, instead of assuming every response contains one text value.

for item in response.output:
    print(item.type)

A tool-enabled request can include tool-related items as well as text. A refusal or incomplete result also needs an explicit path in the application. Use the response object’s documented fields rather than parsing a display string.

What should you check when an SDK request fails?

Read the exception type and request context first. The SDK documents typed errors, request IDs, timeouts and automatic retries. A malformed request needs a correction, while a transient connection or rate-limit failure may need a bounded retry policy.

SymptomCheckResponse
Authentication errorKey exists and belongs to the intended projectSet or replace the key without logging it
Rate limitAPI response and account limitsQueue or slow requests; retry transient failures carefully
Connection failureNetwork, proxy and endpoint reachabilityRetry transient errors with a finite policy
Invalid requestModel name, parameter and input shapeCorrect the request instead of repeating it
TimeoutTask duration and configured timeoutSet a suitable limit and handle timeout explicitly

The SDK retries selected transient failures by default. Application-level retries should account for those attempts so one user action does not create an unexpectedly large number of requests. Preserve a returned request ID because it can help correlate a support report with server-side records.

Keep keys and sensitive prompt contents out of ordinary logs.

Is openai.ChatCompletion.create() deprecated?

That module-level call belongs to the pre-1.0 interface and does not match current client-instance usage. Current code creates a client and calls a resource method. Existing Chat Completions integrations can use the client’s chat completions resource.

Choose the endpoint according to the feature and migration needs.

Should I use a synchronous or asynchronous client?

Use the synchronous client in a regular script or handler. Choose AsyncOpenAI when the surrounding application already uses asyncio and can await network calls. While an async call waits for the API, the event loop can handle other work.

It does not shorten model computation time.

When does streaming help?

Streaming yields output events as they arrive, allowing an interface to show partial text before generation finishes. The application must consume the stream and decide what to do if the connection ends partway through a response. A batch process that needs a complete answer before its next operation can use a normal request.

Event handling depends on the API endpoint, so follow the installed SDK version’s example.

What does tool calling do?

A tool call lets a model request an application-described action. Application code validates its arguments before running the operation, then returns the result to the model. The model does not execute Python functions by itself.

Enforce authorization in code before a consequential action.

When should I use the Agents SDK?

The Agents SDK is a separate, higher-level library for building agent workflows. Start with the standard Python client when the application only needs direct API requests. Read the Agents SDK documentation when orchestration features are part of the requirement.

How do I find the SDK documentation and installed version?

The official Python library repository links to the API reference and its generated library API documentation. Consult the repository for Python-specific method signatures, then use the API reference for endpoint behavior. The installed package version is a separate fact from the API model catalog, so check both when a copied argument is rejected.

Read release notes when upgrading across SDK versions, since the library and service API can evolve on different schedules. For a mismatch, compare the installed method signature with the current repository documentation before changing unrelated dependencies.

python -m pip show openai

This command reports the package metadata for the interpreter selected by python. If the import works in one terminal but fails in an editor, compare their interpreter paths and environment activation before reinstalling anything.

How should I test code that calls the API?

Keep request-building logic separate from code that sends the request. Unit tests can verify the input and response handling with a mock client, without spending API credits. A smaller integration test can check authentication and network configuration against the OpenAI service, but it needs a test key and should avoid sensitive data.

Do not treat a mocked response as proof that the service accepted a request. It only verifies your local control flow. Record which layer a test covers so a passing unit test is not confused with a successful API call.

Conclusion: Start with the Responses API

The OpenAI Python SDK provides a client layer, while your application remains responsible for credentials, model choice and safe handling of results. For new text-generation code, start with the Responses API described in the official Python README, and keep the key outside the program.

Read the official Python SDK documentation, the API quickstart and the API reference. For higher-level agent workflows, see the Agents SDK. Python reads environment values through the standard library.

See AskPython’s guides to reading and setting environment variables and creating and importing Python modules when you split the client setup into application files.

FAQ

These answers cover common setup and API questions.

How do I set the OpenAI API key in Python?

Set OPENAI_API_KEY in the environment before starting Python, then create a client with OpenAI(). Keep the value out of source control.

What Python version does the SDK require?

The official openai-python README states Python 3.10 or later.

Which API should a new Python integration start with?

The official Python library README presents the Responses API as the primary API for interacting with models.

Ninad
Ninad

A Python and PHP developer turned writer out of passion. Over the last 6+ years, he has written for brands including DigitalOcean, DreamHost, Hostinger, and many others. When not working, you'll find him tinkering with open-source projects, vibe coding, or on a mountain trail, completely disconnected from tech.

Articles: 136