How to call OpenAI API from JavaScript
Quick answer
Use the official
openai JavaScript SDK by installing it via npm, setting your API key in environment variables, and calling client.chat.completions.create() with your desired model and messages. This approach ensures secure, efficient access to OpenAI models like gpt-4o.PREREQUISITES
Node.js 18+OpenAI API key (free tier works)npm install openai
Setup
Install the official OpenAI JavaScript SDK and set your API key as an environment variable for secure access.
npm install openai Step by step
This example demonstrates a complete, runnable Node.js script that calls the OpenAI API to generate a chat completion using the gpt-4o model.
import { config } from 'dotenv';
config();
import { OpenAI } from 'openai';
const client = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });
async function run() {
const response = await client.chat.completions.create({
model: 'gpt-4o',
messages: [
{ role: 'user', content: 'Hello, how do I call the OpenAI API from JavaScript?' }
]
});
console.log(response.choices[0].message.content);
}
run(); output
Hello! To call the OpenAI API from JavaScript, use the official OpenAI SDK, set your API key in environment variables, and invoke the chat completion endpoint as shown.
Common variations
You can use async/await or promise syntax, switch models like gpt-4o-mini, or stream responses for real-time output. The SDK supports all these patterns.
import { OpenAI } from 'openai';
const client = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });
// Using promises
client.chat.completions.create({
model: 'gpt-4o-mini',
messages: [{ role: 'user', content: 'Tell me a joke.' }]
}).then(response => {
console.log(response.choices[0].message.content);
}); output
Why did the developer go broke? Because he used up all his cache!
Troubleshooting
- If you get an authentication error, verify your
OPENAI_API_KEYis set correctly in your environment. - For network errors, check your internet connection and firewall settings.
- If the model name is invalid, confirm you are using a current model like
gpt-4oorgpt-4o-mini.
Key Takeaways
- Use the official OpenAI JavaScript SDK installed via npm for best compatibility.
- Always store your API key securely in environment variables, never hardcode it.
- Call
client.chat.completions.create()with the model and messages to get chat completions. - You can switch models or use streaming easily with the same SDK methods.
- Check environment setup and model names if you encounter errors.