OpenAI API API in JavaScript
OpenAI API API in JavaScript
This guide shows you how to integrate the OpenAI API into your JavaScript application. GPT-4, GPT-3.5, DALL-E, Whisper, and Embeddings API for natural language processing, image generation, and speech recognition.
Prerequisites
- JavaScript installed on your system
- An OpenAI API API key (sign up at https://platform.openai.com)
- Basic familiarity with HTTP APIs
Installation
npm install node-fetch
# or use built-in fetch in Node 18+
Basic Usage
const API_KEY = process.env.API_KEY || 'YOUR_API_KEY';
const BASE_URL = 'https://api.openai.com';
async function callApi() {
const response = await fetch(`${BASE_URL}/v1/resources`, {
headers: {
'Authorization': `Bearer ${API_KEY}`,
'Content-Type': 'application/json'
}
});
const data = await response.json();
console.log('Status:', response.status);
console.log(data);
return data;
}
callApi().catch(console.error);
Error Handling
async function callApiWithRetry(url, options, maxRetries = 3) {
for (let attempt = 0; attempt < maxRetries; attempt++) {
try {
const response = await fetch(url, options);
if (response.status === 429) {
const retryAfter = parseInt(response.headers.get('Retry-After') || '60');
console.log(`Rate limited. Waiting ${retryAfter}s...`);
await new Promise(resolve => setTimeout(resolve, retryAfter * 1000));
continue;
}
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
return await response.json();
} catch (error) {
console.error(`Attempt ${attempt + 1} failed:`, error.message);
if (attempt === maxRetries - 1) throw error;
await new Promise(resolve => setTimeout(resolve, Math.pow(2, attempt) * 1000));
}
}
}
callApiWithRetry(`${BASE_URL}/v1/resources`, {
headers: { 'Authorization': `Bearer ${API_KEY}` }
}).then(console.log).catch(console.error);
Advanced Usage
class OpenaiClient {
constructor(apiKey, baseUrl = 'https://api.openai.com') {
this.apiKey = apiKey;
this.baseUrl = baseUrl.replace(/\/$/, '');
}
async request(method, path, options = {}) {
const url = `${this.baseUrl}/v1${path}`;
const response = await fetch(url, {
method,
headers: {
'Authorization': `Bearer ${this.apiKey}`,
'Content-Type': 'application/json',
...options.headers
},
body: options.body ? JSON.stringify(options.body) : undefined,
...options
});
if (!response.ok) {
const error = await response.json().catch(() => ({}));
throw new Error(`API Error: ${error.message || response.statusText}`);
}
return response.json();
}
async listResources(params = {}) {
const query = new URLSearchParams(params).toString();
return this.request('GET', `/resources${query ? '?' + query : ''}`);
}
async createResource(data) {
return this.request('POST', '/resources', { body: data });
}
async getResource(id) {
return this.request('GET', `/resources/${id}`);
}
}
const client = new OpenaiClient(process.env.API_KEY);
client.listResources({ limit: 50 })
.then(data => console.log(`Found ${data.data.length} resources`))
.catch(console.error);
Best Practices
- Store your API key in an environment variable, never in source code
- Implement retry logic with exponential backoff for 429 and 5xx errors
- Set reasonable timeouts (10-30 seconds) for all API calls
- Log request IDs from response headers for debugging
- Cache responses where appropriate to reduce API calls