Using the ChatGPT API in NodeJS
NicolasBrondinBernard
Harness the power of the world's most popular artificial intelligence (LLM) in your applications!

Article published on 04/06/2025, last updated on 10/08/2026
In this tutorial, you'll discover that talking to ChatGPT directly from its API is as easy as pie!
And this is thanks in particular to the fact that OpenAI provides their own SDK for NodeJS.
Let's start with the first step, the least fun but essential for the rest of the tutorial, setting up the project.
Setting up the project
Getting your API key
First of all, you should know that every call to the ChatGPT API costs money.
But don't worry, the prices are very low.
Each call consumes a few "tokens", and with just a few euros, you can use several million tokens!
To start using your tokens, you need to get your API key. To do so, go to: https://platform.openai.com/apps
Choose
API, then log in by clickinglogin, then in the left panel click onAPI keys
You can then click on the "Create new secret key" button, and copy the key that has been generated for you.
Storing your key
Make sure to store your key in a configuration file called .env, inside your project folder, like this:
OPENAI_API_KEY=XX-XXXX-XXXXXXXXXXXX
Never share this key, and never add it to a Git repository (add .env to your .gitignore)
Checking your credit balance
In the left panel on OpenAI, navigate to Billing to check that you have some credits in the "Free Trial" section.
If this is not the case, you will need to add a payment method, and purchase some credits.
Be careful, your balance may take a few minutes to update on OpenAI's side, it's possible that your first API calls will come back with the "Insufficient Credits" error.
Creating the basics of the script
Now that we have our API key in the .env file of our project, we're going to be able to install the dependencies.
Run the command
npm install --save dotenv openaiin your terminal.
Next, you'll need to create an index.js file and paste in the following code:
const dotenv = import('dotenv');
dotenv.config();
// La création du client doit se faire après l'initialisation de dotenv, car le SDK récupère directement la variable `OPENAI_API_KEY`
const OpenAI = import("openai");
const client = new OpenAI();
The rest of the tutorial will take place in this
index.jsfile.
Using the SDK
For our tutorial we're going to use the SDK's responses API, which is the replacement version for chat.completion (now deprecated).
We can finally talk to ChatGPT:
const response = await client.responses.create({
model: "gpt-5.2",
input: [
{ role: "system", content: "Tu es un assistant poète, ton style est moderne et ton langage soutenu. Tu n'ajoute aucun formattage à tes réponses." },
{ role: "user", content: `Rédige un poème de 4 vers, avec des rhymes sous la forme ABBA, sur le thème de la programmation` },
]
});
console.log(response.output_text);
Note that:
- the
systemrole lets you send configuration instructions to the AI - the user role lets you chat directly and ask for a response
Let's now see what happens when we run this code.
Result
To launch our script, simply open a terminal at the root of the project, and run the command: node index.js
And here's what will be displayed by our console.log:
Dans la nuit de l’écran, je compose un algorithme clair,
Les variables murmurent, et la logique se révèle,
Chaque bug, lentement, se dissout puis se révèle,
Au bout du code, enfin, le programme tient, presque clair.
Of course, keep in mind that you'll get a different result every time you run your script.
Understanding the response
You'll have noticed that to display the AI's response, we went and fetched the output_text property. This property is not part of the API itself but of the official SDK, which concatenates all the API's text responses into a single string.
If you want details on the properties of the response object, you can check out the official documentation
There is other important additional information in the API response:
outputwhich will contain each individual response (message) from the chatusagewhich will tell you the number of tokens used to process the request and generate a response
Using the Vision API to describe an image
It's also possible to send files, such as images, to ask ChatGPT to analyze it.
Instead of sending a simple message in input, we'll now send a message of type input_image, like this:
const response2 = await client.responses.create({
model: "gpt-4.1-mini",
input: [{
role: "user",
content: [
{ type: "input_text", text: "Décris cette image" },
{
type: "input_image",
image_url: "https://lirp.cdn-website.com/1b3c7062/dms3rep/multi/opt/shutterstock_1308748093-1920w.jpg",
},
],
}],
});
console.log(response2.output_text);
You can also send images in Base64 format, as explained in the official documentation
Deprecated feature
With the chat.completion API it was possible to provide a seed and generate reproducible responses.
This feature disappeared with the new versions of the API (but is available in
chat.completionfor now)
Full code
Here's the full code of the index.js file used in this tutorial:
import dotenv from "dotenv";
dotenv.config();
import OpenAI from "openai";
const client = new OpenAI();
const response = await client.responses.create({
model: "gpt-5.2",
input: [
{ role: "system", content: "Tu es un assistant poète, ton style est moderne et ton langage soutenu. Tu n'ajoute aucun formattage à tes réponses." },
{ role: "user", content: `Rédige un poème de 4 vers, avec des rhymes sous la forme ABBA, sur le thème de la programmation` },
]
});
console.log(response);
const response2 = await client.responses.create({
model: "gpt-4.1-mini",
input: [{
role: "user",
content: [
{ type: "input_text", text: "Décris cette image" },
{
type: "input_image",
image_url: "https://lirp.cdn-website.com/1b3c7062/dms3rep/multi/opt/shutterstock_1308748093-1920w.jpg",
},
],
}],
});
console.log(response2.output_text);
And there you go, you now know how to use the ChatGPT API in NodeJS!
Complete courses, exercises and certificates to really learn programming!
4.8 average rating
No comments yet