Install the OpenAI Python SDK and Make Your First API Call

In Blog 01, we explored what the OpenAI Python SDK does and where it fits in an application. Now it’s time to use it. By the end of this tutorial, you’ll have a small Python project that sends a prompt to an OpenAI model and prints the response in your terminal. Along the way, you’ll learn how to isolate project dependencies, install the official SDK, and keep your API key out of source code.

This lesson focuses on a working first request rather than every option available in the SDK. We’ll use the Responses API with a minimal example, then explain the few lines you need to understand today. Later lessons cover the client configuration and Responses API in greater depth.

Prerequisites

Before starting, make sure you have:

  • Python 3.10 or newer: The current official Python SDK requires Python 3.10+. Check your version with
Bash
python --version or python3 --version.
  • A terminal and code editor: Any editor works; VS Code is a convenient option.
  • An OpenAI API account: Use the OpenAI API platform to create and manage API keys.
  • API billing or available credits: ChatGPT subscriptions and API billing are separate. Check your API project’s billing and usage limits before making requests.

Security and cost: API requests may incur charges. Never publish an API key, paste it into a screenshot, or commit it to Git. Create a dedicated project key where possible and monitor usage.

flowchart LR
    A["Python App<br/>main.py"] -->|"SDK request"| B["OpenAI API"]
    B -->|"Model inference"| C["AI Model"]
    C -->|"Generated response"| B
    B -->|"API response"| A

    style A fill:#dbeafe,stroke:#2563eb,color:#1e3a8a
    style B fill:#dcfce7,stroke:#16a34a,color:#166534
    style C fill:#f3e8ff,stroke:#9333ea,color:#581c87

1. Create a Python project and virtual environment

A virtual environment keeps dependencies for this tutorial separate from other Python projects. Create a directory and move into it:

Bash
mkdir openai-first-request
cd openai-first-request

Create a virtual environment:

Bash
python -m venv .venv

On some macOS and Linux installations, use python3 instead of python. Activate the environment with the command for your operating system:

EnvironmentActivation command
macOS / Linuxsource .venv/bin/activate
Windows PowerShell.venv\Scripts\Activate.ps1
Windows Command Prompt.venv\Scripts\activate.bat

Your terminal may display (.venv) after activation.

2. Install the OpenAI Python SDK

With the environment active, install the official package:

Bash
pip install --upgrade openai python-dotenv

Check that Python can import the package:

Bash
pip show openai

The version printed will depend on when you install the package; there is no single expected number for this tutorial.

3. Configure your API key securely

Create an API key from the OpenAI API key settings. We will store the key in a project-root .env file and use the python-dotenv package to load it when the script starts. This keeps credentials out of the Python source code.

Create a file named .env beside main.py:

Bash
OPENAI_API_KEY=your-api-key-here

Replace the placeholder locally with your own API key. Do not share the real .env file or commit it to a repository. If you publish example project files, include a safe .env.example containing placeholders instead. A local .env file is a development convenience; production systems should use their hosting platform’s secret-management facilities.

Create a .gitignore file for your project:

Bash
.venv/
.env
__pycache__/

The .gitignore entry keeps .env out of future Git commits. The file does not load itself, your the script must call load_dotenv() before creating the OpenAI client.

4. Write your first Python script

Create main.py in the project directory and add:

Bash
from dotenv import load_dotenv
from openai import OpenAI

load_dotenv()
client = OpenAI()

response = client.responses.create(
    model="gpt-4.1-mini",
    input="Explain what a Python function is in two sentences.",
)

print(response.output_text)

The model identifier is an example, not a guarantee that every API project has access to it. If the API reports that the model is unavailable, choose an accessible text-capable model from the current model catalog.

This code has five essential parts:

  1. from dotenv import load_dotenv: Imports the helper for loading values from a local .env file.
  2. load_dotenv(): Loads the local configuration into the process environment before the API client is initialized.
  3. OpenAI(): Creates a client that reads OPENAI_API_KEY from the environment.
  4. client.responses.create(...): Sends the prompt and selected model to the Responses API.
  5. response.output_text: Provides a convenient way to read the generated text from the response.

The SDK runs inside your Python process and the API and model are remote services. Your code sends a request over the network and waits for a response.

5. Run the script and inspect the output

With your .env file saved in the project directory and the virtual environment activated, run:

Bash
python main.py

If authentication, model access, network connectivity, and billing are configured correctly, the terminal will print an explanation of a Python function.

Optional: Connect the SDK to a local LLM

The OpenAI Python SDK is an HTTP client, not a model runtime. Although the example above sends requests to OpenAI’s hosted API, you can point the same client library at a local server that exposes an OpenAI-compatible API. This is useful if you already run a model through Ollama or LM Studio.

SettingOpenAI-hosted APIOllama (default)LM Studio (default local server)
API base URLSDK defaulthttp://localhost:11434/v1http://localhost:1234/v1
API keyReal OpenAI API key requiredNo real key required; pass a placeholder to this SDKUsually no real key required for a default local server; SDK may need a placeholder
Model nameAvailable OpenAI model IDModel installed locallyModel identifier shown in LM Studio
Model executionHosted remotelyOn your machineOn your machine

Example with Ollama: First install and start Ollama, then download a suitable model using its documented model name. Ensure the server is reachable on its default port, 11434. In this optional example, replace your-installed-model with the name of a model you have actually downloaded.

For the local example, use these values in your project-root .env file instead of the hosted-API configuration:

Bash
LOCAL_LLM_BASE_URL=http://localhost:11434/v1
LOCAL_LLM_MODEL=your-installed-model

Create local_main.py:

Bash
import os

from dotenv import load_dotenv
from openai import OpenAI

load_dotenv()

client = OpenAI(
    base_url=os.getenv("LOCAL_LLM_BASE_URL"),
    api_key="ollama",  # SDK placeholder; not a real OpenAI key
)

response = client.chat.completions.create(
    model=os.environ["LOCAL_LLM_MODEL"],
    messages=[
        {"role": "user", "content": "Explain a Python function in two sentences."}
    ],
)

print(response.choices[0].message.content)

This optional snippet deliberately uses the Chat Completions-compatible endpoint to demonstrate a commonly supported local-server workflow. The main lesson’s OpenAI-hosted example uses client.responses.create().

Do not assume a local server implements the Responses API, tool calling, structured outputs, or streaming identically

Security: A local server may not require authentication on localhost. Do not expose its port to the public internet or an untrusted network without appropriate access controls. Local inference avoids hosted-model API charges for those requests, but still uses your computer’s resources.

6. Common errors and troubleshooting

SymptomLikely causeWhat to check
ModuleNotFoundError: No module named 'openai'SDK installed into a different Python environmentActivate .venv and rerun python -m pip install openai
Missing API key / client initialization errorOPENAI_API_KEY not set in the running shellCheck that .env exists beside main.py, contains OPENAI_API_KEY, and is loaded with load_dotenv() before OpenAI()
Authentication error (401)Invalid or revoked API keyGenerate or select a valid key for the intended API project
Quota or billing error (often 429)Insufficient credits or a usage/spend limitCheck API billing, balance, project limits, and the error code
Rate limit error (429)Too many requests for the applicable limitReduce request frequency; don’t assume every 429 means missing credits
Model access errorModel identifier unavailable to the projectVerify the model name and project access in the current model catalog
Connection or timeout errorNetwork, proxy, or connectivity issueCheck connectivity and retry carefully

Avoid printing your API key while troubleshooting. If a secret is accidentally exposed, revoke it and create a replacement.

7. What you have built

You now have a minimal but complete Python-to-OpenAI workflow

  • a virtual environment
  • an installed SDK
  • an API key loaded from a local .env file
  • a script that sends a prompt and prints the result.

The example intentionally keeps configuration simple so you can see the core sequence without extra abstractions.

In Blog 03 — Understanding the OpenAI Client, we’ll look more closely at the OpenAI() object, client configuration, and how the SDK manages requests.

Official references

Leave a Reply

Your email address will not be published. Required fields are marked *