Skip to content

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 modelGemini 3.8 Flash and its siblings. The engine, in the certificate’s car analogy. You never touch it directly
The APIthe interface over the internet: you send a request with your text and your key, you get a response. A contract, not a program
The SDKa small library in your language that writes the request for you, so you call a function instead of assembling HTTP by hand
The appwhat the certificate builds. A user interface plus code that calls the API on the user’s behalf
The Gemini app and your AI Studio app sit at the bottom of this stack. Everything above is what the certificate does not show you.

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.


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 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.


Two SDKs, same shape. Install:

Terminal window
# Python
pip install -U google-genai
# JavaScript / TypeScript
npm install @google/genai

Set the key as an environment variable - both SDKs read it automatically, so it never appears in your code:

Terminal window
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.


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.

generateContent - legacy
  • 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.
Interactions - current
  • An Interaction is a complete turn in a conversation or task, held server-side.
  • You continue with previous_interaction_id and 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 more interesting change is that an Interaction is not just an answer. It holds an ordered timeline of steps, which you can read:

Step typeWhat it is
user_inputYour message
model_thoughtThe model’s internal reasoning, when thinking is enabled
function_callA request to invoke a tool
function_resultWhat the tool returned
model_outputThe 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.

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.",
)

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.

  • stream=True returns the response in chunks as it is generated, so a user sees text appearing rather than a spinner. You handle events and watch for step.delta to pick up text as it arrives. Streams are resumable via last_event_id, which matters on a flaky connection.
  • background=True runs a long task asynchronously, which requires store=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.

Two features do more for real applications than any amount of prompt wording, and neither appears in the certificate.

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 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.


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:

ToolWhat it does
Google SearchGrounds the answer in live search results - the mechanism behind the knowledge cutoff workaround: lookup rather than recall
Code executionThe model writes and runs code to compute an answer. The right tool for arithmetic, exactly as in data analysis
URL contextFetches and reads specific URLs you name
File searchRetrieval over files you have uploaded
Computer useOperating an interface
Google MapsPlace and location data

Remember they are interaction-scoped: re-specify tools on every turn, or the second turn quietly has none.


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.

ModelModel IDForPrice per million tokens (in / out)
Gemini 3.8 Flashgemini-3.8-flashThe 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 Flashgemini-3.7-flashPrior generation, intricate coding and multi-step work-
Gemini 3.5 Flash-Litegemini-3.5-flash-liteHigh-throughput routine tasks$0.30 / $2.50
Gemini 3.8 Livegemini-3.8-liveReal-time voice, no reasoning delay-
Gemini 3.8 Live Extended Thinkinggemini-3.8-live-extended-thinkingLive audio with deeper background reasoning-
Gemini 3.8 Flash TTSgemini-3.8-flash-ttsStudio-grade expressive speech, 130 languages-
Nano Banana Progemini-3-pro-image4K images, precise text renderingno free tier
Nano Banana 2gemini-3.1-flash-imageProduction-scale image generationno free tier
Veo 3.1veo-3.1-generate-previewCinematic video with synchronised audiono free tier
Gemini Omni Flashgemini-omni-1.1-flashVideo generation, editing and interpolationno free tier
Gemini Embedding 2gemini-embedding-2-previewMultimodal embeddings for semantic search-

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.


Six levers, in roughly descending order of effect.

  1. 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.

  2. 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.

  3. Let caching work. Chaining with previous_interaction_id gives higher implicit cache hit rates, which is cheaper than resending history yourself. Explicit caching remains available on legacy generateContent for a large fixed context reused many times.

  4. Batch anything not interactive. The Batch API - still on generateContent rather 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.

  5. Control the thinking. Thinking is on by default on current models; generation_config takes a thinking_level to 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.

  6. 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.


Before you write any code
  • Key in an environment variable or secret manager, never in source, never in the browser, never in a notebook.
  • .gitignore covers 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.
Before anyone else uses it
  • 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.


Next: Beyond Gemini → - the other providers, the three categories of build tool, MCP and A2A, and where to deploy.