Getting started overview

This guide provides a structured approach for developers to initiate their work with OpenAI's API. It focuses on the fundamental steps required to go from account creation to a successful first API call. OpenAI offers various models, including large language models (LLMs) such as GPT-3.5 Turbo and GPT-4, and image generation models like DALL-E 3, accessible through a unified API OpenAI API overview. Developers can interact with the API using official SDKs for Python and Node.js, or direct HTTP requests.

The process generally involves signing up for an account, generating an API key, and then making a request to an API endpoint. OpenAI provides a free credit tier for new users to explore the platform without immediate charges OpenAI pricing details. Understanding the available models and their pricing is recommended before extensive usage.

Quick Reference Table

Step What to Do Where
1. Sign Up Create an OpenAI Platform account OpenAI Signup Page
2. Generate API Key Create a new secret API key OpenAI API Keys Dashboard
3. Install SDK (Optional) Install Python or Node.js library OpenAI Python Library Documentation / OpenAI Node.js Library Documentation
4. Configure Key Set your API key as an environment variable Local development environment
5. Make First Request Send a basic prompt to a model Code editor or terminal
6. Explore Models Experiment with different models and parameters OpenAI Models Overview / OpenAI Playground

Create an account and get keys

To begin, you need an OpenAI platform account. This account provides access to the API dashboard where API keys are managed and usage is monitored.

  1. Sign Up for an OpenAI Account: Navigate to the OpenAI signup page. You can register using an email address, or authenticate via Google or Microsoft accounts.
  2. Verify Account: Follow the prompts to verify your email address and provide any necessary details, such as your organization name.
  3. Access API Keys Dashboard: Once logged in, go to the API keys section of your dashboard.
  4. Generate a New Secret Key: Click on "+ Create new secret key." A unique key will be displayed. This key is sensitive and should be treated like a password. Store it securely immediately, as it will only be shown once. If lost, you will need to generate a new one and revoke the compromised key.
  5. Set Environment Variable: It is recommended to set your API key as an environment variable rather than hardcoding it directly into your application code. This practice enhances security. For example, in a Unix-like shell, you might use: export OPENAI_API_KEY='your_secret_api_key'. Your application can then access this variable without exposing the key in source control. This is a common security practice for API keys, as detailed in general best practices for developer environment variables.

Your first request

With an account and API key ready, you can now make your first request. This example demonstrates a simple text completion request using the GPT-3.5 Turbo model, which is often a cost-effective choice for initial testing OpenAI API pricing.

Using Python SDK

First, install the OpenAI Python library:

pip install openai

Then, create a Python file (e.g., first_request.py) and add the following code:

import openai
import os

# Ensure your API key is set as an environment variable
# Example: export OPENAI_API_KEY='sk-...' in your terminal
openai.api_key = os.getenv("OPENAI_API_KEY")

if openai.api_key is None:
    print("Error: OPENAI_API_KEY environment variable not set.")
    exit()

def get_completion(prompt, model="gpt-3.5-turbo"):
    messages = [{"role": "user", "content": prompt}]
    response = openai.chat.completions.create(
        model=model,
        messages=messages,
        temperature=0.7 # Controls randomness: higher values mean more random output
    )
    return response.choices[0].message.content

prompt_text = "What is the capital of France?"
response_content = get_completion(prompt_text)
print(response_content)

Run the script:

python first_request.py

Using Node.js SDK

First, initialize your project and install the OpenAI Node.js library:

npm init -y
npm install openai

Then, create a JavaScript file (e.g., first_request.js) and add the following code:

import OpenAI from 'openai';

// Ensure your API key is set as an environment variable
// Example: export OPENAI_API_KEY='sk-...' in your terminal
const openai = new OpenAI({
  apiKey: process.env.OPENAI_API_KEY,
});

async function getCompletion(prompt, model = "gpt-3.5-turbo") {
  if (!openai.apiKey) {
    console.error("Error: OPENAI_API_KEY environment variable not set.");
    process.exit(1);
  }

  try {
    const chatCompletion = await openai.chat.completions.create({
      messages: [{
        role: 'user',
        content: prompt
      }],
      model: model,
      temperature: 0.7,
    });
    return chatCompletion.choices[0].message.content;
  } catch (error) {
    console.error("Error making OpenAI API call:", error);
    throw error;
  }
}

const promptText = "What is the capital of Germany?";
getCompletion(promptText)
  .then(responseContent => console.log(responseContent))
  .catch(error => console.error("Failed to get completion:", error));

Run the script:

node first_request.js

Using cURL (HTTP Request)

For direct HTTP requests without an SDK, you can use cURL. Replace YOUR_API_KEY with your actual secret API key.

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": "Tell me a short story about a brave knight."}] }'

This command sends a POST request to the chat completions endpoint, requesting a short story. The Authorization header uses a Bearer token, a common method for API authentication described by OAuth 2.0 Bearer Token Usage.

Common next steps

After successfully making your first API call, consider these next steps to deepen your integration and optimize usage:

  • Explore Different Models: OpenAI offers various models for different tasks, including text generation (GPT series), image generation (DALL-E 3), speech-to-text (Whisper), and embeddings. Review the OpenAI models documentation to understand their capabilities and optimal use cases.
  • Understand Parameters: Experiment with parameters like temperature (creativity/randomness), max_tokens (output length), and top_p (sampling method) to fine-tune model behavior for your specific application.
  • Manage Usage and Costs: Monitor your API usage through the OpenAI usage dashboard. Set usage limits and alerts to manage costs, especially if you anticipate higher volumes. Refer to the OpenAI pricing page for detailed cost information per model and token.
  • Implement Error Handling: Integrate robust error handling into your application to manage API rate limits, authentication errors, and other potential issues.
  • Secure API Keys: Reiterate the importance of keeping API keys confidential. Avoid hardcoding keys and instead use environment variables or secret management services.
  • Explore Advanced Features: Investigate features like the Assistants API for building stateful, conversational experiences, or Fine-tuning for adapting models to specific datasets.
  • Review Rate Limits: Be aware of the OpenAI rate limits applied to API requests, which can vary by model and account tier. Implement retry logic with exponential backoff for production applications.

Troubleshooting the first call

Encountering issues during your first API call is common. Here are some troubleshooting tips:

  • AuthenticationError: Incorrect API key provided:
    • Check API Key: Ensure the API key copied from the dashboard is correct and hasn't been truncated or altered.
    • Environment Variable: Verify that the OPENAI_API_KEY environment variable is correctly set and accessible in your execution environment. Restart your terminal or IDE if necessary after setting it.
    • Key Status: Confirm your API key is active in the API keys dashboard.
  • RateLimitError: Rate limit exceeded:
    • Initial Limits: New accounts often have lower rate limits. Wait a few moments and try again.
    • Usage Tier: If consistent, check your OpenAI usage page. You might need to add billing information to increase limits.
    • Backoff Strategy: For production, implement an exponential backoff strategy for retries, as described in common AWS API error handling practices.
  • BadRequestError: Invalid request body or similar HTTP 4xx error:
    • JSON Structure: Double-check the JSON payload for your request. Ensure it matches the OpenAI Chat Completions API reference, especially for required fields like model and messages.
    • Model Name: Verify that the model name (e.g., gpt-3.5-turbo) is spelled correctly and is an available model.
    • Content Type: Ensure the Content-Type: application/json header is set for HTTP requests.
  • Connection Issues (e.g., network timeout):
    • Internet Connectivity: Confirm your internet connection is stable.
    • Firewall/Proxy: Check if a firewall or proxy is blocking outbound connections to api.openai.com.
  • No output or empty response:
    • Prompt Issues: Review your prompt. Sometimes very vague or ambiguous prompts can lead to minimal or unexpected responses.
    • max_tokens: Ensure max_tokens is not set too low if you expect a longer response.