Thuta Learning
IntermediateAIbeginner

Calling an AI API with JavaScript

Relax. We'll talk through this in plain words — no textbook voice.

What you'll walk away with

  • Understand Calling an AI API with JavaScript without the intimidation factor
  • Get hands-on practice trying it yourself
  • Spot the common pitfalls and sidestep them with a smile

Call the Responses API server-side using the OpenAI JavaScript SDK, and pull out the output.

Let's think about it this way for a moment

The official JavaScript SDK simplifies authentication, request formatting, and response parsing. If you put OPENAI_API_KEY in an environment variable, the SDK picks it up automatically. The example below uses gpt-5.6, the current model alias.

Calling an AI API with JavaScript lesson illustration
AI APIs — Calling an AI API with JavaScript

Let's connect this to everyday life

In a new project, run npm install openai and create the client from an ES module file. In production, you'll need to add try/catch, timeouts, logging, and user authentication.

Let's try it hands-on together

javascript
import OpenAI from "openai";

const client = new OpenAI();

const response = await client.responses.create({
  model: "gpt-5.6",
  input: "REST API ဆိုတာဘာလဲ မြန်မာလိုတိုတိုရှင်းပြပါ။",
});

console.log(response.output_text);
You should see
An answer from the AI will appear in the terminal.

5-minute try-it

Swap the input for a question you're curious about. Add a prompt to keep the answer under 150 words, and add error handling too.

A quick word of caution

Don't treat AI output as the final, guaranteed-correct answer. For anything important — critical facts, code, or user data — have a human review it before you use it.

OpenAI API QuickstartOpenAI

OpenAI — Using GPT-5.6OpenAI

Easy traps

  • Committing the .env file to Git
  • Calling the SDK directly from a browser component

Exercise

Swap the input for a question you're curious about. Add a prompt to keep the answer under 150 words, and add error handling too.

You'll know it worked when: An answer from the AI will appear in the terminal.

Calling an AI API with JavaScript | Thuta Learning