LearnAIAI Builder deep dives ← Roadmap

Station 3 · Code + AI

Talk to AI with code

So far you've talked to AI in a chat box. But to build things, your program needs to talk to the model directly — no human typing in the middle. The doorway that makes that possible is called an API.

3 of 9 · ~8 min

What you'll walk away with

Concept 1

What even is an API?

API stands for Application Programming Interface. That's a mouthful, so ignore the words for a second. An API is just a doorway one program uses to ask another program to do something and hand back a result.

You use APIs all day without seeing them. When a weather app shows today's forecast, it didn't measure the sky — it asked a weather company's API "what's the forecast for this zip code?" and got numbers back. Your app doesn't need to know how the other side works. It just needs to know how to ask.

🍽️ Analogy: the restaurant waiter

Think of a restaurant. You are your app. The kitchen is the AI model — powerful, but you can't walk into it. The waiter is the API: the messenger between you two. You give the waiter an order (a request), the waiter carries it to the kitchen, and brings back your dish (the response). You never cook, and you never see the kitchen. You just order and receive.

That's the whole shape of every AI feature you'll build: send a request, get a response. The "kitchen" happens to be a giant next-word predictor (Station 1), but from your app's side it's just: ask, wait, receive.

Concept 2

The request → response loop

When your app talks to an AI model, the order you send has a specific shape. You send the conversation so far (as a list of messages) plus a few settings. You get back generated text.

Each message has two parts: a role (who's talking) and content (what they said). The roles you'll use most:

Here's the smallest useful example. It's Python, and it's real — this is genuinely close to what you'd type. (The exact SDK name and setup vary a little by provider, but the shape is the same everywhere.)

first_api_call.py
# 1. Bring in the provider's library and set up a client
from ai_provider import Client

client = Client(api_key=os.environ["AI_API_KEY"])

# 2. Send the request: which model, plus a list of messages
response = client.chat(
    model="some-fast-model",
    messages=[
        {"role": "system",  "content": "You are a friendly tutor."},
        {"role": "user",    "content": "Explain gravity in one sentence."},
    ],
    temperature=0.7,      # creativity dial (more on this below)
    max_tokens=100,        # length cap on the reply
)

# 3. Read the model's reply out of the response
reply = response.choices[0].message.content
print(reply)
what comes backGravity is the invisible pull that draws objects with mass toward one another — it's why you stay on the ground and why the Moon orbits Earth.

Read it top to bottom and it's just three moves: set up a client, send messages, read the reply. That's it. Everything fancier you ever build — a homework helper, a chatbot, an agent — is this same loop, wrapped in more code around it.

Concept 3

API keys — your app's password

Notice that api_key in the code above. An API key is a long secret string the provider gives you. It proves the request is coming from your account, so they know who's using the model — and who to bill.

Think of it exactly like a password for your app. When you sign up with an AI provider, you generate a key that looks something like a random jumble of letters and numbers. Your code sends it with every request, and the provider checks: "Yep, that's a real account — go ahead."

⚠️ The #1 rule: never expose your key

A real API key is money and identity. Anyone who has it can run requests on your account and run up your bill. So: never paste a real key into public code, chat messages, screenshots, or a GitHub repo. If a key ever leaks, delete it in your provider's dashboard immediately and make a new one. The safe habit: keep keys in an environment variable (that os.environ["AI_API_KEY"] trick above) — never typed directly into the code you share.

This trips up almost every beginner at least once. People commit a key to GitHub, and within minutes bots have found it and started spending. Building the "keys stay secret" reflex now saves you a real headache later.

Concept 4

Tokens, cost & the context window

AI models don't read letters or whole words — they read tokens. A token is a chunk of text, very roughly 4 characters, or about ¾ of a word. "Cat" might be one token; "unbelievable" might be two or three.

Why should you care about tokens? Because you pay per token — both for the tokens you send (your prompt and the whole conversation so far) and the tokens the model sends back. Short question, short answer = cheap. A giant document pasted in plus a long reply = more tokens = more cost. (Every provider prices this differently, so always check their pricing page — no magic number here.)

🧾 Analogy: ingredients and counter space

Back to the kitchen. Tokens are the ingredients you pay for — the more you use in an order, the higher the bill. The context window is the counter space: the model can only lay out so many ingredients at once. Send a conversation bigger than the counter, and the oldest stuff falls off the edge — the model literally can't "see" it anymore.

That "counter space" has a real name: the context window — the maximum number of tokens the model can consider at one time (your messages plus its reply, added together). It's why very long chats can get expensive (you're resending the whole history every turn) and why, past a certain length, a model seems to "forget" what you said way back at the start. It didn't forget — that text slid off the counter.

Rough rule

1 token ≈ 4 characters

So ~750 words is roughly 1,000 tokens. Handy for guessing how big a request is before you send it.

Two costs

Input + output both count

You pay for what you send and what comes back. Long context you resend every turn adds up fast.

Concept 5

Two settings worth knowing

Requests take optional settings that change how the model responds. As a beginner you really only need two — and you saw both in the code above.

Temperature — the creativity dial

Temperature controls how random the model's word-picking is. Remember from Station 1 that the model ranks likely next words. Temperature decides how boldly it strays from the safest pick:

A rule of thumb: turn it down when you want the same reliable answer every time, turn it up when you want fresh, different ideas.

Max tokens — the length cap

Max tokens sets a ceiling on how long the reply can be. Set it to 50 and you'll get a short answer; set it to 1,000 and the model has room to write a lot. It's both a way to keep responses tidy and a way to protect your bill — the model can't hand you (and charge you for) 2,000 tokens if you capped it at 200.

🔑 The core idea

Every AI feature you'll ever build is the same loop: send messages + settings → get generated text back. The API is the waiter. Your key is the password. Tokens are the meter. Temperature and max tokens are the two knobs you'll actually turn. Master this one page and the code side of AI stops being scary.

Checkpoint

A friend pastes their real API key straight into a public GitHub repo so their code "just works." What's the problem?

"Nothing — keys are meant to be shared so the code runs anywhere." "Anyone can grab that key and run up charges on their account — keys must stay secret." "It's fine as long as the repo is named something boring."

An API key is a password for your account. Public keys get found by bots within minutes and used to spend your money. Keys belong in an environment variable or a private secrets file — never in shared code, chats, or screenshots. If one leaks, revoke it and make a new one right away.

Try it yourself — 15 minutes, no install

Send your first request in a playground

Most providers (OpenAI, Anthropic, Google) have a free web playground or API console — a page where you can send a request from your browser without writing any code. Let's use it to see everything from this lesson live:

  1. Open any provider's playground or API console (search "[provider] playground"). Sign in with a free account.
  2. In the system box, type a role for the model — e.g. "You are a pirate who explains science." In the user box, ask "Why is the ocean salty?" Send it and read the reply.
  3. Find the temperature slider. Set it low and send again — then set it high and send again. Notice how the answers get more predictable vs. more colorful.
  4. Set max tokens very low (like 20) and resend. Watch the reply get cut off — proof the cap is real.
  5. Look for a token count somewhere on the page. Watch the number climb as your conversation gets longer. That's your meter running.

Keep: jot the shape you just used — system + user messages in, generated text out, tokens metered, temperature and max tokens as knobs. That's the whole API in one line.


Recap. An API is the waiter between your app and the AI kitchen: you send an order (a list of role/content messages plus settings), you get back a dish (generated text). Your API key is your app's password — keep it secret, always. You pay per token (~4 characters each), and the context window is how much text the model can hold on its counter at once. The two knobs you'll actually turn are temperature (creativity) and max tokens (length). Next up, we make those messages themselves much smarter.