Python OpenAI API: Step-by-Step Setup
The OpenAI API is the most widely adopted interface for accessing state-of-the-art language models in production. Setting it up in Python takes fewer than five minutes and requires only an API key and one pip install command. This guide walks you through acquiring credentials, installing the official openai Python client library, and making your first authenticated API call.
Getting Your OpenAI API Key
The first step is obtaining an API key from OpenAI. Navigate to https://platform.openai.com/account/api-keys, sign in with your OpenAI account (create one free at https://openai.com if needed), and click "Create new secret key". Copy the key immediately—OpenAI only displays it once. Store it securely in an environment variable, a .env file (local development only), or a password manager; never hardcode keys in version control.
For production applications, OpenAI recommends storing keys in environment variables. On Linux/macOS, run export OPENAI_API_KEY="sk-..." in your terminal. On Windows PowerShell, use $env:OPENAI_API_KEY = "sk-...". To persist across sessions, add the variable to your system environment settings or use a .env file with the python-dotenv package. The openai client library automatically reads from the OPENAI_API_KEY environment variable if present.
You will also need a billing account with a payment method on file. OpenAI offers free trial credits ($5–20 USD) that expire after three months; after that, usage is billed per token. Check your usage and set spending limits at https://platform.openai.com/account/billing/overview.
Installing the openai Python Client
The official openai Python library is the recommended way to interact with the API. Install it using pip:
pip install openai
As of 2026, the openai package requires Python 3.7+. Verify your Python version:
python --version
If you need Python 3.9 or later for async/await patterns (covered in later articles), upgrade via python.org, Homebrew, or your system package manager.
Making Your First API Call
Once the client is installed and your API key is set as an environment variable, you can make your first request in three lines of code:
from openai import OpenAI
client = OpenAI() # reads OPENAI_API_KEY from environment
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[
{
"role": "user",
"content": "What is the capital of France?"
}
]
)
print(response.choices[0].message.content)
Save this as hello_openai.py and run it:
python hello_openai.py
Expected output:
The capital of France is Paris.
The request creates a chat completion using the gpt-4o-mini model (a fast, cost-effective model available in 2026). The response object contains a list of choices, each with a message containing the assistant's reply. The content field holds the text.
Understanding the Request Structure
Every API call to OpenAI requires three parameters: a model name, a messages list, and optional parameters for behavior (temperature, max_tokens, etc.). The messages parameter is a list of dictionaries with role and content keys. Three roles exist: user (human input), assistant (model response), and system (optional instruction for the model's behavior). This structure is covered in depth in the Chat Messages API article.
Handling Authentication Errors
If you see AuthenticationError: Incorrect API key provided, verify that your key is valid and correctly set in the environment. Run this test:
import os
from openai import OpenAI
print("API Key present:", bool(os.getenv("OPENAI_API_KEY")))
client = OpenAI()
print("Client initialized successfully")
If the key is present but authentication fails, regenerate it in the OpenAI dashboard—keys are sometimes revoked for security reasons.
If you see RateLimitError: Rate limit exceeded, your account is hitting OpenAI's usage limits. Check your billing status and usage at https://platform.openai.com/account/billing/usage. If you exceed free credits or your payment method is invalid, requests are rejected.
Verifying API Access Works
To confirm your setup is complete, run a quick diagnostic:
from openai import OpenAI
client = OpenAI()
# Test the API with a simple completion
completion = client.chat.completions.create(
model="gpt-4o-mini",
messages=[{"role": "user", "content": "Reply with a single word."}],
max_tokens=10
)
print(f"Success! Model responded: {completion.choices[0].message.content}")
print(f"Tokens used: {completion.usage.completion_tokens}")
This request is minimal and inexpensive. If it runs without errors, your authentication, credentials, and billing are correctly configured.
Key Takeaways
- Obtain a free API key from platform.openai.com and store it in the
OPENAI_API_KEYenvironment variable. - Install the official openai library:
pip install openai. - Create an OpenAI client:
client = OpenAI()(the library reads the environment variable automatically). - Make a chat completion request with
model,messages, and optional parameters likemax_tokens. - Check billing and usage limits at https://platform.openai.com/account/billing/overview.
- Authentication errors indicate invalid API keys; rate limit errors indicate billing issues or usage caps.
Frequently Asked Questions
Can I use multiple API keys in one application?
Yes. Create additional API keys in the OpenAI dashboard and pass them explicitly: client = OpenAI(api_key="sk-..."). You might use different keys for different projects, users, or billing accounts to track usage independently.
Which model should I use for production?
As of June 2026, gpt-4o-mini is the recommended fast and cost-effective model for most applications. gpt-4o is more capable but slower and more expensive. Check https://platform.openai.com/docs/models for the latest available models and pricing.
Is the .env file approach safe?
Using .env files is safe for local development if you add .env to .gitignore and never commit it. For production, always use environment variables set by your deployment platform (Heroku, AWS, Docker secrets, etc.) and never commit credentials to git.
What if my API key is exposed in a GitHub commit?
Immediately regenerate the key in the OpenAI dashboard—exposed keys can be abused. If you accidentally commit a key, use git filter-branch to rewrite history and remove it (after regenerating the key to invalidate the old one).