How to Use ChatGPT API in NodeJS?
Last Updated :
25 Jul, 2024
ChatGPT is a very powerful chatbot by OpenAI that uses Natural Language Processing to interact like humans. It has become very popular among developers and is being widely used for some of its state-of-the-art features like understanding and interpreting code and even generating code based on textual requirements. OpenAI has not only provided its functionality as a chatbot on the website but has also provided an API to help integrate ChatGPT into our applications and projects using which we can make an HTTP request and utilize the response appropriately.

In this article, we will have a look at the step-by-step procedure to integrate ChatGPT API in the Node.js project.
Using ChatGPT in Node.js Application
Adding ChatGPT functionalities to our large-scale NodeJS Application will make that more efficient for the users. So in this article, we will see step by step implementation of where to retrieve the API key, and how to create a NodeJS application that uses OpenAI API, that will work similarly to ChatGPT, and you can make conversation with ChatGPT using that application. Here are the complete steps for using ChatGPT in NodeJS Application.
1. Creating a Node.js Application
First of all, we will create a directory for the project say, chatgpt-api-nodejs, either using GUI or by pasting the below command in the terminal at the desired location in our machine:
mkdir chatgpt-api-nodejs
Now, change the directory to the newly created folder:
cd chatgpt-api-nodejs
To initialize the node.js project, run the below command which creates a package.json file to keep track of project details
npm init -y
We will use axios for making HTTP requests and dotenv for managing environment variables.
npm install axios dotenv
2. Retrieving the OPENAI API Key
To use the API, we need to generate the API keys.
A. For that, go to OpenAI and either sign up or login (if you already have an account).

Create OpenAI account
B. Then click on the API option

Creating ChatGPT API key
C. On the left corner you will see API keys, click on it and it will open API keys section. Click on ‘Create new secret key, to crate a new one.

Create new Secret Keys
D. Click on the ‘Create new secret key’ button. It will open up a dialog box asking for the name of the key which is optional. After you are done, click ‘Create secret key’.

Create new Secret Keys
E. A dialog box will appear displaying your secret key/API key. Copy it and ‘done’. Save the key safely and do not share it with anyone.

Create new Secret Keys
Create a new file to create an environment variable for storing the API key
touch .env
In the file, create a variable OPENAI_API_KEY and replace "YOUR OPEN AI API KEY" with your API key (keeping the quotes)
OPENAI_API_KEY="YOUR OPEN AI API KEY"
3. Implementing NodeJS Application
Create a javascript file say, index.js, and paste the below code inside it.
JavaScript
//index.js
const axios = require("axios");
const dotenv = require("dotenv");
const readline = require("readline");
// Load environment variables from .env file
dotenv.config();
// OpenAI API key
const apiKey = process.env.OPENAI_API_KEY;
// Function to call the ChatGPT API
async function callChatGPT(prompt) {
const url = "https://api.openai.com/v1/chat/completions";
const headers = {
"Content-Type": "application/json",
Authorization: `Bearer ${apiKey}`,
};
const data = {
model: "gpt-3.5-turbo",
messages: [
{ role: "system", content: "You are a helpful assistant." },
{ role: "user", content: prompt },
],
};
try {
const response = await axios.post(url, data, { headers });
const result = response.data.choices[0].message.content;
return result;
} catch (error) {
console.error(
"Error calling ChatGPT API:",
error.response ? error.response.data : error.message
);
throw error;
}
}
// Create an interface for user input
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
// Prompt the user for input
rl.question("Enter your input: ", async (prompt) => {
try {
const response = await callChatGPT(prompt);
console.log("ChatGPT response:", response);
} catch (error) {
console.error("Error:", error.message);
} finally {
rl.close();
}
});
4. Run the Application
To run the app, run the below command in terminal
node index.js
The above code takes the input prompt through the command line and prints the response generated by the ChatGPT model.
Output

How to Use ChatGPT API in NodeJS? – FAQs
Is ChatGPT API free?
Yes, but it has some limitations after that we have to Pay for use of API. To use the API, one needs to create an account on OpenAI which can be created for free.
What are the rate limits for ChatGPT API?
As per the official OpenAI documentation, the number of requests per minute is limited to 3 RPM (for the free tier) and tokens per minute to 40,000 TPM.
Can ChatGPT API be brought to commercial use?
Yes, ChatGPT API can be integrated into the projects for commercial use. For that, one might need to purchase the pay-as-you-go plan to get an increased rate limit for API calls. ChatGPT API is well designed keeping in mind the scalability as the application grows.
Please Login to comment...