Getting started overview
Integrating the OpenAI API into an application involves several steps, from initial account setup to executing the first API call. This guide focuses on the foundational process required to begin development, covering account registration, API key management, and a practical example of making a request. OpenAI provides access to various models, including large language models (LLMs) like GPT-4o and GPT-3.5 Turbo, as well as models for image generation (DALL-E 3), speech-to-text transcription (Whisper), and embeddings generation OpenAI API overview. The API operates on a pay-as-you-go model, where usage is billed based on factors such as the specific model used and the number of input and output tokens processed OpenAI API pricing details.
The primary SDKs supported for interacting with the OpenAI API are Python and Node.js, with comprehensive documentation and examples available for both OpenAI API reference. Developers can also interact with the API directly via HTTP requests.
Quick Reference Steps
| Step | What to Do | Where |
|---|---|---|
| 1. Account Creation | Register for an OpenAI account. | OpenAI signup page |
| 2. API Key Generation | Create a new secret API key. | OpenAI API keys page |
| 3. Environment Setup | Install the appropriate SDK (Python/Node.js) or set up cURL for direct HTTP. | Local development environment |
| 4. First Request | Execute a simple API call (e.g., chat completion). | Code editor/terminal |
| 5. Usage Monitoring | Review API usage and costs. | OpenAI usage dashboard |
Create an account and get keys
Before making any API calls, an OpenAI account is required. The registration process is standard, typically involving an email address and password, followed by email verification. Once registered, access to the OpenAI platform dashboard is granted.
API keys are essential for authenticating requests to the OpenAI API. These keys link API usage to your account and are critical for billing and security. Each key is a unique identifier that should be treated as sensitive information, similar to a password. API keys are generated through the OpenAI platform dashboard.
- Navigate to the API Keys Page: After logging into your OpenAI account, go to the API keys section of the dashboard.
- Generate New Secret Key: Click the "Create new secret key" button. A new key will be displayed. This is the only time the full key will be visible; it is recommended to copy and store it securely immediately.
- Store Your Key: Store the API key in a secure location. For development, it's common practice to store it as an environment variable rather than hardcoding it directly into your application code. This prevents accidental exposure and simplifies key rotation. For example, in a Linux/macOS environment, you might use
export OPENAI_API_KEY='your_secret_key_here'. For Windows, useset OPENAI_API_KEY=your_secret_key_herein Command Prompt or$env:OPENAI_API_KEY='your_secret_key_here'in PowerShell.
OpenAI API usage is billed on a pay-as-you-go basis, with no free tier beyond initial credits for new accounts OpenAI pricing models. Monitoring usage is important to manage costs, which can be done through the usage dashboard.
Your first request
This section demonstrates how to make a basic chat completion request using the OpenAI API. We will provide examples for both Python and Node.js, the primary SDKs, and a cURL example for direct HTTP interaction.
Python Example
First, install the OpenAI Python library:
pip install openai
Then, create a Python file (e.g., first_request.py) with the following content:
import openai
import os
# Ensure your API key is set as an environment variable named OPENAI_API_KEY
# For example: export OPENAI_API_KEY='sk-...' in your terminal
client = openai.OpenAI(
api_key=os.environ.get("OPENAI_API_KEY"),
)
def get_chat_completion(prompt):
try:
response = client.chat.completions.create(
model="gpt-3.5-turbo", # Or "gpt-4o" for newer models
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": prompt}
]
)
return response.choices[0].message.content
except openai.APIConnectionError as e:
print(f"The server could not be reached: {e.__cause__}") # an underlying error occurred
except openai.RateLimitError as e:
print(f"A 429 status code was received; we should back off a bit.") # Too many requests
except openai.APIStatusError as e:
print(f"Another non-200-range status code was received") # e.g. 400, 500
print(e.status_code)
print(e.response)
if __name__ == "__main__":
user_prompt = "What is the capital of France?"
completion = get_chat_completion(user_prompt)
if completion:
print(f"Assistant: {completion}")
Run the script from your terminal:
python first_request.py
Node.js Example
First, initialize your project and install the OpenAI Node.js library:
mkdir openai-first-request
cd openai-first-request
npm init -y
npm install openai dotenv
Create a .env file in your project root and add your API key:
OPENAI_API_KEY=your_secret_key_here
Then, create an index.js file with the following content:
require('dotenv').config();
const OpenAI = require('openai');
const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY,
});
async function getChatCompletion(prompt) {
try {
const chatCompletion = await openai.chat.completions.create({
model: 'gpt-3.5-turbo', // Or 'gpt-4o' for newer models
messages: [
{ role: 'system', content: 'You are a helpful assistant.' },
{ role: 'user', content: prompt }
],
});
return chatCompletion.choices[0].message.content;
} catch (error) {
if (error instanceof OpenAI.APIError) {
console.error(error.status); // e.g. 400
console.error(error.message); // e.g. The authentication token you passed was invalid...
console.error(error.code); // e.g. 'invalid_api_key'
console.error(error.type); // e.g. 'invalid_request_error'
} else {
// Non-API error
console.log(error);
}
}
}
(async () => {
const userPrompt = "What is the capital of France?";
const completion = await getChatCompletion(userPrompt);
if (completion) {
console.log(`Assistant: ${completion}`);
}
})();
Run the script from your terminal:
node index.js
cURL Example (Direct HTTP Request)
For direct HTTP requests, you can use cURL. Replace YOUR_API_KEY with your actual OpenAI API key.
curl https://api.openai.com/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_API_KEY" \
-d '{"model": "gpt-3.5-turbo", "messages": [{"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": "What is the capital of France?"}]}'
Common next steps
After successfully making your first API call, several common next steps can enhance your application and understanding of the OpenAI API:
- Explore Different Models: Experiment with other available models like GPT-4o for more advanced reasoning, DALL-E 3 for image generation, or Whisper for speech-to-text transcription. Each model has specific capabilities and pricing OpenAI model pricing.
- Understand Rate Limits: OpenAI implements rate limits to ensure fair usage and service stability. Familiarize yourself with these limits to design robust applications that handle potential throttling gracefully OpenAI rate limit guide. Implement retry logic with exponential backoff for production applications, a common practice described in guides like the Google Cloud retry requests documentation.
- Manage API Keys Securely: Beyond environment variables, consider using a secret management service (e.g., AWS Secrets Manager, Google Secret Manager, Azure Key Vault) for production deployments to further secure API keys and other sensitive credentials.
- Monitor Usage and Costs: Regularly check your OpenAI usage dashboard to track token consumption and associated costs. Set up spending limits and alerts if available.
- Implement Error Handling: Develop comprehensive error handling mechanisms to gracefully manage API errors, network issues, and unexpected responses. The provided Python and Node.js examples include basic error handling.
- Explore SDK Features: Dive deeper into the features offered by the official Python or Node.js SDKs, which often provide conveniences for common tasks, streaming responses, and managing context.
- Review Best Practices: Consult OpenAI's official documentation for best practices regarding prompt engineering, safety guidelines, and optimizing API calls for performance and cost efficiency OpenAI prompt engineering guide.
Troubleshooting the first call
When encountering issues with your initial OpenAI API request, consider the following common problems and their solutions:
- Invalid API Key:
- Symptom:
401 Unauthorizederror, often with a message like "Incorrect API key provided." - Solution: Double-check that the API key copied from the OpenAI API keys page is correct and that no leading/trailing spaces or incorrect characters are present. Ensure it's correctly loaded into your environment variable or directly in your code (though environment variables are recommended).
- Symptom:
- Missing API Key:
- Symptom:
401 Unauthorizederror, potentially indicating a missing Authorization header. - Solution: Verify that the API key is being passed in the
Authorization: Bearer YOUR_API_KEYheader for direct HTTP requests, or that the SDK is correctly picking up the key from your environment variable or explicit configuration.
- Symptom:
- Rate Limit Exceeded:
- Symptom:
429 Too Many Requestserror. - Solution: This is less common on a very first call but can occur if multiple rapid attempts are made. Wait a short period and retry. Review OpenAI rate limits for your account tier.
- Symptom:
- Invalid Request Body/Parameters:
- Symptom:
400 Bad Requesterror with messages detailing specific parameter issues (e.g., "‘messages’ is a required property", "‘model’ must be a string"). - Solution: Carefully compare your request payload with the OpenAI Chat Completions API reference. Ensure all required fields are present, correctly formatted (e.g., JSON structure, data types), and that the model name is valid.
- Symptom:
- Network Connectivity Issues:
- Symptom: Connection timeouts or "failed to connect" errors.
- Solution: Check your internet connection. If you are behind a corporate firewall or proxy, ensure it allows outgoing connections to
api.openai.comon port 443.
- Incorrect Model Name:
- Symptom:
404 Not Foundor400 Bad Requestwith a message indicating the model does not exist. - Solution: Verify that the model name (e.g.,
gpt-3.5-turbo,gpt-4o) is spelled correctly and is currently available via the API OpenAI models overview.
- Symptom: