Course 9, lesson 81 of 100, Ages 14+
Using an AI API
Talking to AI with code
Like I’m 5
An API is like a waiter. Your app gives the waiter an order, the waiter takes it to the AI kitchen, and brings back the answer.
The big idea
An API (application programming interface) lets your program talk to an AI model over the internet. Your code sends a request with a prompt and settings; the API sends back the model's reply as data.
A typical request includes the model name, a list of messages, a maximum length and sometimes tools the model may call. Keep your API key secret like a password, handle errors, and log usage so costs don't surprise you.
Examples
- Request: Send: model, messages and max tokens. Receive: the reply text and token counts.
- Keys: Store the API key on your server, never in a public web page.
- Errors: Retry politely when the service is busy, rather than hammering it.
How it works
- An API lets your own app send a message to an AI model and get a reply back.
- Each request carries a key that proves who you are. Keep keys secret, just like passwords.
- You pay for the tokens you send and receive, and settings like temperature change how creative the replies are.
Check your understanding
- Why must you keep an API key secret?
- Options: It works like a password for your account; It makes the AI slower; It’s only a decoration.
Answer: It works like a password for your account. Anyone with your key could use your account and run up costs. - Where should an API key live?
- Options: Somewhere secret, like your server's settings; In public web page code; In a social media post.
Answer: Somewhere secret, like your server's settings. Anyone with your key can use your account, so keep it private.
Remember
APIs connect your app to AI. Keep your keys secret.
Talk about it
If an API is a waiter, what would you order from the AI kitchen?
Go deeper
A typical request sends a model name, a system prompt, the conversation so far and settings such as maximum tokens and temperature. It returns generated text plus token counts. Real apps add error handling, retries when rate-limited, caching, and keep keys on a server, never in the app itself.