ChatGPT API Integration Guide
ChatGPT API Integration Guide
🔑 1. Get an API Key
- Go to the OpenAI Platform.
- Sign in or create an account.
- Navigate to API Keys under your profile.
- Click Create new secret key and copy it securely.
⚠️ Keep your API key private—never expose it in client-side code or public repositories.
📦 2. Install the OpenAI SDK
For Python:
pip install openai
For Node.js:
npm install openai
💬 3. 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);
🛡️ 4. 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;
📈 5. 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.")
🧠 6. 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.
🌐 7. 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
- https://platform.openai.com/docs/api-reference
- https://openai.com/pricing
- https://platform.openai.com/docs/guides/prompt-engineering