Calling an API from Code

Send a request from JavaScript and read the assistant's reply.

Calling an LLM from code is just an HTTP POST with a JSON body and an API key in the header. Here is the pattern in JavaScript using fetch.

Steps

  1. Build the messages array.
  2. POST it to the chat endpoint with your key.
  3. Read the assistant message out of the JSON response.

Example

Example · javascript
const res = await fetch('https://api.example-llm.com/v1/chat', {
  method: 'POST',
  headers: {
    'Authorization': `Bearer ${process.env.API_KEY}`,
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    model: 'llm-medium',
    messages: [{ role: 'user', content: 'Say hello in French.' }]
  })
});

const data = await res.json();
console.log(data.choices[0].message.content); // "Bonjour !"

When to use it

  • A Node.js backend calls the OpenAI API on each user query and returns the AI reply as a REST JSON response to the front end.
  • A Python data pipeline calls the API to classify thousands of customer reviews, storing the label returned in each response.
  • A browser extension sends the current page's selected text to the API and displays the AI summary in a popup.

More examples

Call API from JavaScript (Node.js)

Shows the minimal Node.js SDK call — import the client, create a request, log the reply.

Example · javascript
import OpenAI from 'openai';

const client = new OpenAI(); // reads OPENAI_API_KEY from process.env
const response = await client.chat.completions.create({
  model: 'gpt-4o-mini',
  messages: [{ role: 'user', content: 'Explain closures in JavaScript.' }]
});
console.log(response.choices[0].message.content);

Call API from Python

Mirrors the JavaScript example in Python using the official SDK.

Example · python
from openai import OpenAI

client = OpenAI()  # OPENAI_API_KEY from environment
response = client.chat.completions.create(
    model='gpt-4o-mini',
    messages=[{'role': 'user', 'content': 'Explain closures in Python.'}]
)
print(response.choices[0].message.content)

Call API via raw HTTP with curl

Makes the same request with curl and pretty-prints the JSON response — useful for quick debugging.

Example · shell
curl https://api.openai.com/v1/chat/completions \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gpt-4o-mini",
    "messages": [{"role": "user", "content": "Explain closures."}]
  }' \
| python3 -m json.tool

Discussion

  • Be the first to comment on this lesson.