Building Your First AI Feature with the OpenAI API
Learn to call the OpenAI API from a Node.js app, handle responses, and build a simple AI-powered feature end to end.
Overview
We'll build a tiny app that turns a user's text into a polished summary using the OpenAI chat completions API.
Step 1: Get an API key
Create an API key at platform.openai.com. Keep it secret — never commit it to git.
Step 2: Make your first call
Use the official SDK to send a chat completion request.
Step 3: Handle the response
Parse the message content and surface it to your user. Always handle errors gracefully.
Best practices
Example Snippet / Template
import OpenAI from "openai";
const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });
const response = await openai.chat.completions.create({
model: "gpt-4o-mini",
messages: [
{ role: "system", content: "Summarize the user's text in 2 sentences." },
{ role: "user", content: userInput }
],
max_tokens: 100
});
console.log(response.choices[0].message.content);