Back
beginner
AI Fundamentals

Hands-on: API Setup and Your First Model Call

Learn what an AI API call is, how messages work, and how to make a safe first request

25 min read· API· Hands-on· JavaScript· Python

Hands-on: API Setup and Your First Model Call

Chat apps are useful, but APIs let you build your own AI features.

An API call is just your program sending a request to a model provider and receiving a response.

What you send

Most chat-style APIs use messages:

MessagePurpose
system/developerbehavior rules for the app
userwhat the user asks
assistantprior model replies
toolresults from APIs or tools

Your first safe request

Conceptually, the request looks like this:

json
{
  "model": "current-fast-model",
  "messages": [
    { "role": "system", "content": "You are a concise tutor." },
    { "role": "user", "content": "Explain tokens in one paragraph." }
  ]
}

The exact SDK changes by provider. The important idea is stable: choose a model, send messages, receive output.

Keep keys out of the browser

Never put a secret API key in frontend JavaScript.

Use:

text
browser -> your server route -> model provider

Not:

text
browser -> model provider with secret key

Minimal server-side flow

ts
export async function POST(request: Request) {
  const { question } = await request.json();

  if (!question || question.length > 2000) {
    return Response.json({ error: "Invalid question" }, { status: 400 });
  }

  // Call your chosen provider here using a server-side API key.
  // Return only the final answer or a validated structured object.
  return Response.json({ answer: "Model response goes here." });
}

This example is intentionally small. The lesson is the shape, not a giant pasted implementation.

What to configure

SettingBeginner default
modelcurrent fast or balanced model
temperaturelow for factual tasks, higher for creative tasks
max output tokensset a limit
timeoutfail gracefully
retriesonly for safe requests
loggingmetadata, not secrets

Common errors

ErrorMeaning
invalid API keykey missing or wrong
rate limittoo many requests
context length exceededprompt is too large
schema validation failedoutput did not match expected shape
timeoutprovider took too long

First exercise

Build a route that answers one question:

  1. Accept
    question
    .
  2. Reject empty input.
  3. Ask the model to answer in three bullets.
  4. Return the answer.
  5. Log token count if the SDK provides it.

Knowledge check

Q1: Why should you set max output tokens?

To control cost, latency, and runaway responses.

Q2: Why should frontend code not contain API keys?

Because users can inspect frontend code and steal the key.