How to Use the OpenAI API: A Beginner’s Guide to Setup and First Request
The OpenAI API provides developers with access to powerful models like GPT-4o for chat, text generation, and summarization. This tutorial covers the essentials: getting an API key, installing the SDK, and running your first request.
Step 1: Get Your API Key
Log in to the OpenAI platform, go to the API keys section, and click “Create new secret key.” Copy it immediately and store it securely. Never share your key or commit it to GitHub.
Step 2: Install the SDK
For Python, install the official package with pip:
pip install openai
Set your API key as an environment variable to keep it out of your code:
export OPENAI_API_KEY="your-key-here"
Step 3: Make Your First Request
Create a file named test_openai.py:
from openai import OpenAI
client = OpenAI()
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Say hello in one sentence."}
]
)
print(response.choices[0].message.content)
The messages array controls the conversation. The system message sets the assistant’s behavior, while the user message provides the instruction.
Best Practices
- Use environment variables to secure your API key.
- Test with
gpt-4o-minito keep costs low. - Set
max_tokensto control response length and cost. - Add error handling to manage rate limits and network issues.
Conclusion
You can now call OpenAI models from your code. Next, explore parameters like temperature and streaming to build robust, production-ready applications.