AI

ChatGPT API Integration Guide

ChatGPT API Integration Guide

Get an API Key

  1. Go to the OpenAI Platform.
  2. Sign in or create an account.
  3. Navigate to API Keys under your profile.
  4. Click Create new secret key and copy it securely.

Keep your API key private €”never expose it in client-side code or public repositories.

Install the OpenAI SDK

For Python:

pip install openai

For Node.js:

npm install openai

Make API Call

Python Example

from openai import OpenAI

client = OpenAI(api_key="YOUR_API_KEY")

response = client.chat.completions.create(
    model="gpt-4",  # or "gpt-3.5-turbo"
    messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "Hello! How are you?"}
    ]
)

print(response.choices[0].message.content)

Node.js Example

import OpenAI from "openai";

const openai = new OpenAI({ apiKey: "YOUR_API_KEY" });

const response = await openai.chat.completions.create({
  model: "gpt-4",
  messages: [
    { role: "system", content: "You are a helpful assistant." },
    { role: "user", content: "Hello! How are you?" }
  ]
});

console.log(response.choices[0].message.content);

Secure API Key

Never hardcode your key. Use environment variables:

Python (.env)

OPENAI_API_KEY=your-secret-key

Load with python-dotenv:

from dotenv import load_dotenv
import os
load_dotenv()
api_key = os.getenv("OPENAI_API_KEY")

Node.js

npm install dotenv
require('dotenv').config();
const apiKey = process.env.OPENAI_API_KEY;

Handle Errors & Rate Limits

Always wrap API calls in error-handling blocks:

try:
    response = client.chat.completions.create(...)
except openai.RateLimitError:
    print("Rate limit exceeded.")
except openai.AuthenticationError:
    print("Invalid API key.")

Choose the Right Model

Model Use Case
gpt-4 High accuracy, complex tasks
gpt-3.5-turbo Faster, cheaper, good for most apps
gpt-4-turbo Latest GPT-4 with larger context

See the latest details at OpenAI Models.

Deploy Safely

If building a web app, proxy requests through your backend. Never call the OpenAI API directly from the browser €”it exposes your key.

Additional Resources