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
- Build the messages array.
- POST it to the chat endpoint with your key.
- Read the assistant message out of the JSON response.
Example
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.
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.
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.
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