How to Call an AI API in Node.js (2026): JavaScript Quickstart
ai api javascriptcall llm api nodenodejs ai tutorialai api fetchjavascript ai api

How to Call an AI API in Node.js (2026): JavaScript Quickstart

2026-07-15

Calling an AI API in Node.js

From zero to a working call in JavaScript — LLMs, images and video — using one key so you can switch models without new SDKs. Get a key first: how to get an API key.

Setup

Node 18+ has fetch built in. Keep your key in an env var:

export LINKMODEL_API_KEY="sk_live_..."

Your First LLM Call

const res = await fetch("https://api.linkmodel.ai/v1/chat/completions", {
  method: "POST",
  headers: {
    "Authorization": `Bearer ${process.env.LINKMODEL_API_KEY}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    model: "claude-sonnet-4-6",
    messages: [{ role: "user", content: "Explain event loops in 2 sentences." }],
  }),
});
if (!res.ok) throw new Error(`HTTP ${res.status}`);
console.log(await res.json());

Swap model to gpt-5.6-terra, gemini-3.5-flash, or deepseek-v4-flash — one key, no new client. See multimodal AI API.

Generating an Image (Async)

const r = await fetch("https://api.linkmodel.ai/api/v1/image-generation", {
  method: "POST",
  headers: { "Authorization": `Bearer ${process.env.LINKMODEL_API_KEY}`, "Content-Type": "application/json" },
  body: JSON.stringify({ model: "seedream-5.0-pro", prompt: "Hero banner, clean type, 2K" }),
}).then(x => x.json());
const taskId = r.data.task_id;   // then poll GET /api/v1/query/image-generation?task_id=

Poll GET /api/v1/query/image-generation?task_id=... (or /api/v1/query/video-generation) until the task reports success, then read the result URL.

Never Ship Keys to the Browser

Call the AI API from your backend / serverless function, not client-side — a key in frontend JS is trivially stolen. For apps, proxy through your server (same idea as AI API for mobile apps).

Retries with Backoff

async function call(body, tries = 4) {
  for (let i = 0; i < tries; i++) {
    const r = await fetch(URL, { method: "POST", headers: H, body: JSON.stringify(body) });
    if (r.status !== 429) return r.json();
    await new Promise(s => setTimeout(s, 2 ** i * 1000)); // exponential backoff
  }
  throw new Error("rate limited");
}

See AI API rate limits.

Bottom Line

fetch, one key, and a model string gets you LLMs, images and video from Node — call it server-side, add backoff, and stream long outputs (streaming guide). Confirm endpoints in the docs.

Start free with a $1 credit and run your first call.

Related Posts