Connect to OpenAI from Python
Connect to OpenAI from Python
Section titled โConnect to OpenAI from PythonโThis guide shows the minimal production-appropriate setup for calling OpenAI from Python:
- install the SDK
- store the API key safely
- make a first request
- keep the example easy to adapt
1. Install the SDK
Section titled โ1. Install the SDKโpython -m pip install openai python-dotenv2. Store the API Key
Section titled โ2. Store the API KeyโSet the key as an environment variable.
Windows PowerShell
Section titled โWindows PowerShellโ$env:OPENAI_API_KEY="your-api-key-here"macOS or Linux
Section titled โmacOS or Linuxโexport OPENAI_API_KEY="your-api-key-here"You can also store it in a local .env file for development:
OPENAI_API_KEY=your-api-key-here3. Make a First Request
Section titled โ3. Make a First Requestโfrom openai import OpenAI
client = OpenAI()
response = client.responses.create( model="gpt-5.2", input="Explain retrieval-augmented generation in two short sentences.")
print(response.output_text)Why This Example Uses responses.create
Section titled โWhy This Example Uses responses.createโThe current OpenAI docs position the Responses API as the main path for new text-generation work. If you are copying older tutorials, you may still see chat-completions examples. Those older examples are useful historical context, but this page is intentionally using the newer API shape.
4. Add .env Support for Local Development
Section titled โ4. Add .env Support for Local Developmentโimport osfrom dotenv import load_dotenvfrom openai import OpenAI
load_dotenv()
client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))Common Mistakes
Section titled โCommon Mistakesโ- hardcoding the key in source files
- using the wrong environment variable name
- assuming older SDK examples still reflect the preferred API shape
- coupling your app too tightly to one specific model name
Practical Advice
Section titled โPractical Adviceโ- keep the API key in the environment, not in code
- move model names into config once the app grows
- start with one small test script before integrating into a larger app