Getting started overview
Getting started with the OpenAI API involves a sequence of steps designed to onboard developers quickly. This guide focuses on creating an account, securing API credentials, and executing a foundational API request. The OpenAI API provides access to various models including language models (e.g., GPT-4o, GPT-3.5 Turbo), image generation models (DALL-E 3), and speech-to-text models (Whisper), among others, as detailed in the OpenAI API overview documentation.
Before making your first API call, you will need to:
- Create an OpenAI platform account.
- Generate a secret API key.
- Set up your development environment.
- Construct and send an authenticated request.
The API operates on a pay-as-you-go model, with pricing varying by model and usage, such as the number of input/output tokens for language models or image resolution for DALL-E 3. OpenAI offers a free tier for new users, subject to specific usage limits that vary by model.
Quick Reference Steps
| Step | What to Do | Where to Do It |
|---|---|---|
| 1. Sign Up | Create an OpenAI platform account. | OpenAI Signup Page |
| 2. Get API Key | Generate a new secret API key. | OpenAI API Keys Page |
| 3. Set Environment Variable | Store your API key securely as OPENAI_API_KEY. |
Local development environment (e.g., ~/.bashrc, ~/.zshrc) |
| 4. Install SDK (Optional) | Install the official Python or Node.js SDK. | Terminal (pip install openai or npm install openai) |
| 5. Make First Request | Send a simple API call (e.g., a text completion). | Terminal (cURL) or script (Python/Node.js) |
Create an account and get keys
Access to the OpenAI API requires an account on the OpenAI platform. If you do not already have an account, navigate to the OpenAI signup page and follow the prompts to create one. This typically involves providing an email address, setting a password, and verifying your email.
Once your account is set up and you've logged in, you will need to generate a secret API key. This key authenticates your requests to the API and should be treated with the same security considerations as a password.
- Log in to the OpenAI platform.
- Navigate to the API keys section of your account dashboard.
- Click the "Create new secret key" button.
- A unique key will be displayed. Copy this key immediately, as it will only be shown once.
- Store your API key securely. It is recommended to store it as an environment variable (e.g.,
OPENAI_API_KEY) rather than hardcoding it directly into your application code. This practice aligns with general security recommendations for handling sensitive credentials in development, as outlined in guides like the Microsoft Azure security best practices for application development.
To set an environment variable on Linux/macOS, you can add the following line to your shell's configuration file (e.g., ~/.bashrc, ~/.zshrc) and then source the file:
export OPENAI_API_KEY='YOUR_SECRET_API_KEY'
On Windows, you can set it via the System Properties or using the command prompt:
setx OPENAI_API_KEY "YOUR_SECRET_API_KEY"
Remember to replace 'YOUR_SECRET_API_KEY' with the actual key you generated.
Your first request
After setting up your API key, you can make your first API call. This section demonstrates how to send a simple text completion request using cURL and the official Python SDK.
Using cURL
cURL is a command-line tool for making HTTP requests and is useful for quickly testing API endpoints. Ensure you have cURL installed on your system.
To make a request to the Chat Completions endpoint using the gpt-3.5-turbo model:
curl https://api.openai.com/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $OPENAI_API_KEY" \
-d '{ "model": "gpt-3.5-turbo", "messages": [{"role": "user", "content": "Hello, what is your name?"}] }'
This command sends a POST request with JSON data, including the model and a simple user message. The Authorization header uses your environment variable $OPENAI_API_KEY to authenticate the request.
Using Python SDK
OpenAI provides official SDKs for Python and Node.js, which simplify interaction with the API. This example uses the Python SDK.
1. Install the Python SDK
If you haven't already, install the OpenAI Python library using pip:
pip install openai
2. Create a Python script
Create a file named first_request.py and add the following code:
import openai
import os
# Ensure your API key is set as an environment variable
# openai.api_key = os.getenv("OPENAI_API_KEY") # Older versions
client = openai.OpenAI(api_key=os.environ.get("OPENAI_API_KEY")) # Modern approach
try:
response = client.chat.completions.create(
model="gpt-3.5-turbo",
messages=[
{"role": "user", "content": "What is the capital of France?"}
]
)
print(response.choices[0].message.content)
except openai.APIError as e:
print(f"OpenAI API Error: {e}")
except Exception as e:
print(f"An unexpected error occurred: {e}")
3. Run the script
Execute the Python script from your terminal:
python first_request.py
You should see a response from the model, such as "The capital of France is Paris."
Common next steps
After successfully making your first API call, consider these next steps to further integrate the OpenAI API into your applications:
- Explore different models: The OpenAI Models overview details capabilities and pricing for models like GPT-4o, DALL-E 3 for image generation, and Whisper for speech-to-text.
- Experiment with the Playground: The OpenAI Playground allows you to test prompts and parameters interactively before writing code. This is particularly useful for prompt engineering.
- Review API Reference: Consult the OpenAI API Reference documentation for detailed information on all available endpoints, request parameters, and response structures.
- Implement error handling: Integrate robust error handling into your code to manage API errors, rate limits, and network issues.
- Manage usage and costs: Monitor your API usage through your OpenAI account usage dashboard and understand the pricing structure to control costs.
- Secure API keys: Continue to follow best practices for API key security, such as using environment variables or a secrets management service, and rotating keys periodically.
- Explore advanced features: Look into features like fine-tuning models, using embeddings for semantic search, or leveraging Assistants for stateful conversational applications.
Troubleshooting the first call
If your first API call encounters issues, check the following common problems:
- Incorrect API Key: Double-check that your
OPENAI_API_KEYenvironment variable is correctly set and that the key itself is valid. AnAuthentication erroror401 Unauthorizedresponse typically indicates an issue with the API key. Ensure there are no extra spaces or characters. - Missing Authorization Header: For cURL requests, verify that the
-H "Authorization: Bearer $OPENAI_API_KEY"header is correctly included. For SDKs, ensure the API key is passed during client initialization or set as an environment variable that the SDK can access. - Rate Limits Exceeded: New accounts often have lower initial rate limits. If you receive a
429 Too Many Requestserror, you might be hitting a rate limit. Wait a moment and retry, or review your OpenAI rate limit documentation. - Invalid JSON Payload: Ensure the JSON body of your request is well-formed and adheres to the API's expected schema. Pay close attention to quotation marks, commas, and bracket placement.
- Incorrect Endpoint or Model Name: Verify that the API endpoint (e.g.,
/v1/chat/completions) and the specifiedmodelname (e.g.,gpt-3.5-turbo) are correct and match the OpenAI API reference. - Network Issues: Confirm your internet connection is stable and that no firewall or proxy is blocking your request to
api.openai.com. - Environment Variable Not Loaded: If you set an environment variable, ensure your terminal session has loaded it (e.g., by opening a new terminal or running
source ~/.bashrc). You can test by typingecho $OPENAI_API_KEYin your terminal.