Prompt
How do I call an AI API from Node.js for text classification?
Latest observation
Oct 8, 2026
OpenAI APIWeb search: off
You can call an AI API from Node.js for text classification by sending the text you want classified to a model and asking it to return one of your labels.
Here’s a simple approach using Node.js and fetch.
1) Install Node.js
Make sure you have Node 18+ so fetch is available globally.
2) Example: classify text with an AI API
const apiKey = process.env.OPENAI_API_KEY;
async function classifyText(text) {
const response = await fetch("https://api.openai.com/v1/responses", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${apiKey}`,
},
body: JSON.stringify({
model: "gpt-4.1-mini",
input: [
{
role: "system",
content: "You are a text classifier. Classify the user's text into one of: spam, urgent, normal. Reply with only the label."
},
{
role: "user",
content: text
}
]
}),
});
if (!response.ok) {
throw new Error(`API error: ${response.status} ${await response.text()}`);
}
const data = await response.json();
return data.output_text.trim();
}
(async () => {
const label = await classifyText("Win a free iPhone now!!! Click here.");
console.log(label);
})();
3) Set your API key
Set it in your environment:
export OPENAI_API_KEY="your_api_key_here"
On Windows PowerShell:
$env:OPENAI_API_KEY="your_api_key_here"
4) Notes for classification
For best results:
- Define a small fixed set of labels
- Tell the model to output only one label
- Provide examples if needed
- Validate the returned label in your code
5) Safer parsing example
If you want to make sure the output is one of the allowed labels:
const allowed = new Set(["spam", "urgent", "normal"]);
const label = (await classifyText(text)).toLowerCase();
if (!allowed.has(label)) {
throw new Error(`Unexpected label: ${label}`);
}
6) Using the official SDK
If you prefer the OpenAI SDK:
npm install openai
import OpenAI from "openai";
const client = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });
async function classifyText(text) {
const response = await client.responses.create({
model: "gpt-4.1-mini",
input: [
{
role: "system",
content: "Classify the text into one of: spam, urgent, normal. Reply with only the label."
},
{
role: "user",
content: text
}
]
});
return response.output_text.trim();
}
If you want, I can also show:
- how to do this with structured JSON output
- how to classify into multiple categories
- how to use Express.js to expose a classification endpoint