How to test OpenAI API connection in python
Quick answer
Use the official
openai Python SDK v1 to test your API connection by sending a simple chat completion request with client.chat.completions.create. Ensure your API key is set in os.environ["OPENAI_API_KEY"] and use a current model like gpt-4o to verify connectivity.PREREQUISITES
Python 3.8+OpenAI API key (free tier works)pip install openai>=1.0
Setup
Install the official OpenAI Python SDK version 1 or higher and set your API key as an environment variable.
- Run
pip install openai>=1.0to install the SDK. - Export your API key in your shell:
export OPENAI_API_KEY='your_api_key_here'(Linux/macOS) or set it in Windows environment variables.
pip install openai>=1.0 Step by step
Use this complete Python script to test your OpenAI API connection by sending a simple chat message to the gpt-4o model and printing the response.
import os
from openai import OpenAI
client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
response = client.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": "Hello, OpenAI!"}]
)
print("Response from OpenAI API:")
print(response.choices[0].message.content) output
Response from OpenAI API: Hello! How can I assist you today?
Common variations
You can test the API connection asynchronously or use different models like gpt-4o-mini. For async, use asyncio with await client.chat.completions.acreate(...). Streaming responses are also supported with the SDK.
import os
import asyncio
from openai import OpenAI
async def test_async():
client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
response = await client.chat.completions.acreate(
model="gpt-4o-mini",
messages=[{"role": "user", "content": "Async test"}]
)
print("Async response:", response.choices[0].message.content)
asyncio.run(test_async()) output
Async response: Hello! This is an async test response.
Troubleshooting
- If you get an authentication error, verify your
OPENAI_API_KEYenvironment variable is set correctly. - For network errors, check your internet connection and firewall settings.
- If the model is not found, confirm you are using a current model name like
gpt-4o.
Key Takeaways
- Use the official OpenAI Python SDK v1 and set your API key in environment variables.
- Test connectivity by sending a simple chat completion request to a current model like gpt-4o.
- Async and streaming calls are supported for more advanced testing scenarios.
- Check environment variables and model names if you encounter authentication or model errors.