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:
| Message | Purpose |
|---|---|
| system/developer | behavior rules for the app |
| user | what the user asks |
| assistant | prior model replies |
| tool | results from APIs or tools |
Your first safe request
Conceptually, the request looks like this:
{
"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:
browser -> your server route -> model provider
Not:
browser -> model provider with secret key
Minimal server-side flow
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
| Setting | Beginner default |
|---|---|
| model | current fast or balanced model |
| temperature | low for factual tasks, higher for creative tasks |
| max output tokens | set a limit |
| timeout | fail gracefully |
| retries | only for safe requests |
| logging | metadata, not secrets |
Common errors
| Error | Meaning |
|---|---|
| invalid API key | key missing or wrong |
| rate limit | too many requests |
| context length exceeded | prompt is too large |
| schema validation failed | output did not match expected shape |
| timeout | provider took too long |
First exercise
Build a route that answers one question:
- Accept .
question - Reject empty input.
- Ask the model to answer in three bullets.
- Return the answer.
- 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.