Google AI 11 - The Gemini API in Practice
Added chapter - not part of the certificate.
The certificate takes you from using the Gemini app to building an app in AI Studio, and then stops. It never shows you the thing your app has been calling the whole time.
That is a reasonable curriculum decision - the certificate promises no coding, and it keeps the promise. But it leaves a gap that matters the moment anything you built goes beyond yourself, because three of the most consequential facts about your app live on the other side of that boundary: what it costs, where your key is, and what it is allowed to do. The deployment course bumps into all three - a quota error, a server-side secret, a share link - without explaining any of them.
App, API, SDK: three words for three different things
Section titled “App, API, SDK: three words for three different things”The practical difference between the app and the API is control and liability, in both directions. Through the app you get a polished interface, somebody else’s rate limits and no bill. Through the API you get to decide the model, the parameters, the tools, the retry behaviour and the output format - and you get a bill, a key to protect, and responsibility for everything the thing does.
Getting one
Section titled “Getting one”A Gemini API key comes from AI Studio. If you did the certificate’s app courses you already have one, because AI Studio created it for you and put it in your app - the Secrets panel in settings is where it lives.
The one rule
Section titled “The one rule”The bill follows the key
Section titled “The bill follows the key”The commercial consequence, which the deployment course demonstrates without naming: a deployed AI Studio app uses your key for every user’s calls. Ten people using your dashboard spend against your quota and your bill. That is the real reason a phased rollout matters, and the real reason anything lasting belongs on an organisational account with its own billing.
The smallest working call
Section titled “The smallest working call”Two SDKs, same shape. Install:
# Pythonpip install -U google-genai
# JavaScript / TypeScriptnpm install @google/genaiSet the key as an environment variable - both SDKs read it automatically, so it never appears in your code:
export GEMINI_API_KEY="your-key-here"Then the whole thing, in Python:
from google import genai
client = genai.Client()
interaction = client.interactions.create( model="gemini-3.8-flash", input="Explain how AI works in a few words",)print(interaction.output_text)And in JavaScript:
import { GoogleGenAI } from "@google/genai";
const ai = new GoogleGenAI({});
const interaction = await ai.interactions.create({ model: "gemini-3.8-flash", input: "Explain how AI works in a few words",});console.log(interaction.output_text);That is the entire surface. Everything else in this chapter is additional arguments to that one call.
The Interactions API
Section titled “The Interactions API”What changed
Section titled “What changed”If you have read a Gemini tutorial written before mid-2026, it will show models.generate_content(...). That still works and is fully supported - but it is now labelled legacy. The Interactions API went generally available in June 2026 and is Google’s recommended interface for Gemini, and new agent features ship only through it.
The difference is where conversation state lives.
- Stateless: one request, one response.
- You keep the whole conversation history and resend it every turn.
- Simple, and it means a long chat re-sends - and re-pays for - everything said so far on every single turn.
- An Interaction is a complete turn in a conversation or task, held server-side.
- You continue with
previous_interaction_idand the server retrieves the prior context itself. - Better cache hit rates, so lower cost on multi-turn conversations, plus background execution and resumable streams.
The step timeline
Section titled “The step timeline”The more interesting change is that an Interaction is not just an answer. It holds an ordered timeline of steps, which you can read:
| Step type | What it is |
|---|---|
user_input | Your message |
model_thought | The model’s internal reasoning, when thinking is enabled |
function_call | A request to invoke a tool |
function_result | What the tool returned |
model_output | The final response |
This is what makes a complicated interaction debuggable. The deployment course’s failure - an app returning fast, confident, fictional numbers with no error - is exactly the kind of thing a visible step timeline helps with: you can see whether a tool was called at all, which is precisely what “the responses are both near instant and don’t seem accurate” was intuiting without the evidence.
Continuing a conversation
Section titled “Continuing a conversation”first = client.interactions.create( model="gemini-3.8-flash", system_instruction="You are a concise analyst. Never speculate.", input="Summarise the revenue trend in this data.",)
second = client.interactions.create( model="gemini-3.8-flash", system_instruction="You are a concise analyst. Never speculate.", previous_interaction_id=first.id, input="Now break that down by region.",)Storage, retention and stateless mode
Section titled “Storage, retention and stateless mode”By default store=true and interactions are kept server-side: 1 day on the free tier, 55 days on paid. Paid projects can shorten that to 7, 14 or 28 days in AI Studio, and you can delete an interaction programmatically.
Passing store=false turns storage off entirely - you then manage the conversation history yourself, as with the legacy API. The trade-off is explicit: no previous_interaction_id and no background execution without storage.
For anyone handling personal data under GDPR, that paragraph is the one to read twice. The retention window is a configurable processing decision, not a fixed property of the service.
Streaming and background work
Section titled “Streaming and background work”stream=Truereturns the response in chunks as it is generated, so a user sees text appearing rather than a spinner. You handle events and watch forstep.deltato pick up text as it arrives. Streams are resumable vialast_event_id, which matters on a flaky connection.background=Trueruns a long task asynchronously, which requiresstore=True. This is the right shape for anything that takes minutes - a long document analysis, a research-style task - rather than holding a request open.
Making the output usable
Section titled “Making the output usable”Two features do more for real applications than any amount of prompt wording, and neither appears in the certificate.
Structured output
Section titled “Structured output”Asking for JSON in a prompt gets you JSON most of the time, which is the worst possible reliability: often enough to build on, not often enough to trust. Structured output lets you supply a schema the response must conform to, so the model is constrained rather than asked politely.
This turns “please reply with the fields I need” into a guarantee, and it is what separates a demo from something that can feed the next step of a pipeline without a human looking at it. If your app ever parses the model’s answer, it should be using this.
Function calling
Section titled “Function calling”Function calling lets you describe your own functions - name, purpose, arguments - and have the model request one when it needs it. The model does not run anything; it returns a function_call step, your code executes it, and you pass the result back as a function_result.
That division is the whole safety story. The model decides that a thing should happen; your code decides whether and how. Every check you want - permissions, limits, validation, logging - goes in your code, where it belongs.
Server-side tools
Section titled “Server-side tools”Some tools you do not have to build, because they run on Google’s side. Pass them in tools and the model uses them when relevant:
| Tool | What it does |
|---|---|
| Google Search | Grounds the answer in live search results - the mechanism behind the knowledge cutoff workaround: lookup rather than recall |
| Code execution | The model writes and runs code to compute an answer. The right tool for arithmetic, exactly as in data analysis |
| URL context | Fetches and reads specific URLs you name |
| File search | Retrieval over files you have uploaded |
| Computer use | Operating an interface |
| Google Maps | Place and location data |
Remember they are interaction-scoped: re-specify tools on every turn, or the second turn quietly has none.
Models and prices
Section titled “Models and prices”As of writing. These move, and the authoritative source is the Gemini API pricing and models documentation; AI Studio shows your project’s own active limits.
| Model | Model ID | For | Price per million tokens (in / out) |
|---|---|---|---|
| Gemini 3.8 Flash | gemini-3.8-flash | The most intelligent Flash model: long-horizon software engineering, autonomous agents, complex workflows | $0.75 / $3.75 - introductory, to 31 Dec 2026, then $1.50 / $7.50 |
| Gemini 3.1 Pro | - | Advanced reasoning | $2 / $12 up to 200K tokens; $4 / $18 above |
| Gemini 3.7 Flash | gemini-3.7-flash | Prior generation, intricate coding and multi-step work | - |
| Gemini 3.5 Flash-Lite | gemini-3.5-flash-lite | High-throughput routine tasks | $0.30 / $2.50 |
| Gemini 3.8 Live | gemini-3.8-live | Real-time voice, no reasoning delay | - |
| Gemini 3.8 Live Extended Thinking | gemini-3.8-live-extended-thinking | Live audio with deeper background reasoning | - |
| Gemini 3.8 Flash TTS | gemini-3.8-flash-tts | Studio-grade expressive speech, 130 languages | - |
| Nano Banana Pro | gemini-3-pro-image | 4K images, precise text rendering | no free tier |
| Nano Banana 2 | gemini-3.1-flash-image | Production-scale image generation | no free tier |
| Veo 3.1 | veo-3.1-generate-preview | Cinematic video with synchronised audio | no free tier |
| Gemini Omni Flash | gemini-omni-1.1-flash | Video generation, editing and interpolation | no free tier |
| Gemini Embedding 2 | gemini-embedding-2-preview | Multimodal embeddings for semantic search | - |
The free tier
Section titled “The free tier”Enough to learn on and not enough to run anything:
- Flash and Flash-Lite only. Pro models left the free tier in April 2026.
- Limits are expressed as RPM (requests per minute), RPD (requests per day) and TPM (tokens per minute), and they vary by model and account status - broadly single-digit to ~15 RPM and a few hundred to ~1,000 RPD. No credit card required.
- Check your own, do not hard-code these. Active limits for your project are shown in AI Studio, and the published numbers change.
This is the arithmetic behind the quota error in the debug demo. A free-tier app shared with a handful of colleagues will hit a limit the same afternoon.
Keeping the bill small
Section titled “Keeping the bill small”Six levers, in roughly descending order of effect.
-
Use the smallest model that passes your test. The gap between Flash-Lite at $0.30 and Pro at $4 on long prompts is more than tenfold. Most tasks in this certificate - classification, extraction, reformatting, summarising - run perfectly on Flash-Lite. Start cheap and move up only when output quality actually fails.
-
Send less. Input is billed per token, and a grounding document attached to every request is paid for on every request. The prompting advice to paste only what is relevant turns out to be a cost control as well as a quality one.
-
Let caching work. Chaining with
previous_interaction_idgives higher implicit cache hit rates, which is cheaper than resending history yourself. Explicit caching remains available on legacygenerateContentfor a large fixed context reused many times. -
Batch anything not interactive. The Batch API - still on
generateContentrather than Interactions - processes large volumes asynchronously at roughly half price. If nobody is waiting for the answer, there is no reason to pay for speed. -
Control the thinking. Thinking is on by default on current models;
generation_configtakes athinking_levelto trade cost and latency against intelligence. Reasoning tokens are billed, and a deep-thinking model answering “classify this as urgent or not” is pure waste. -
Cap your output. Output costs roughly five times input. Asking for “three bullets, under 40 words” is a cost decision as much as an editorial one.
Rate limits, errors, and the enterprise path
Section titled “Rate limits, errors, and the enterprise path”Expect to be throttled. A limit returns an error rather than a queue, and the correct response is to retry with exponential backoff - wait a second, then two, then four - rather than retrying immediately in a loop, which makes things worse. The SDKs include retry logic; know that it is there and what it does.
And expect a model to be retired. A model ID pinned in your code is a dependency with an expiry date. When it goes, your app fails in production on a Tuesday. Keep the model name in configuration rather than scattered through your code, and keep a couple of known inputs with known-good outputs so you can tell whether a swap changed behaviour - the hand-rolled evaluation set from the fundamentals.
For anything organisational, the Gemini API is also available through Google Cloud, which is where you go for cloud IAM instead of an API key, consolidated billing, data residency, and the compliance posture an employer’s security review will ask about. The code is nearly identical; the governance is not. If your workflow worksheet turned up a task three colleagues also do, this is the path rather than your personal key.
A security checklist
Section titled “A security checklist”- Key in an environment variable or secret manager, never in source, never in the browser, never in a notebook.
.gitignorecovers your config file. Check it before the first commit, not after.- Decide whose key and whose billing this is.
- Know what data will pass through, and whether it is allowed to.
- Browser calls your server; server calls Gemini.
- Validate every model output before acting on it - never execute, render or query it unchecked.
- Treat user-supplied text, files and URLs as untrusted input.
- Set a spend limit, and know your rate limits.
- Log what was asked and what was answered, for the accountability trail.
- In the EU: if users talk to it, tell them it is AI - Article 50, in force since 2 August 2026.
Revision summary
Section titled “Revision summary”Next: Beyond Gemini → - the other providers, the three categories of build tool, MCP and A2A, and where to deploy.