Thuta Learning
API Tutorial
AdvancedWeb DevelopmentIntermediate

Gemini (Google AI) API

API TutorialLesson 2035 min

What you'll walk away with

  • Send a request to POST /v1beta/interactions with the x-goog-api-key header and a body of model and input
  • Extract the text from model_output steps instead of assuming one fixed response path
  • Read the older generateContent shape, including a blocked prompt that returns no candidates
  • Map error codes such as rate_limit_exceeded and quota_exceeded to retry, wait, fix or stop

Explain it simply

Explain it simply

Google's Gemini API follows the same basic idea as the other AI APIs: you send a prompt as JSON over HTTPS and read the generated text from the JSON that comes back. What makes Gemini a little special for learners is that it currently has two doors. The newer Interactions endpoint is the one Google recommends for new projects, and the older generateContent endpoint is still supported and still appears in thousands of tutorials.

Picture a library with a new reading room and an old one. Both hand you the same book, but the shelves are labelled differently, so a visitor who learned the old labels will look in the wrong place and decide the book is missing.

Problem → Why → Solution

The problem: a year-old tutorial in production

Copy a tutorial from a year ago and you will probably inherit a hard-coded model name, a response path such as candidates[0].content.parts[0].text, a key written into the URL and no handling for anything except success.

Model ids on Google's models page keep moving: older ids are retired or re-routed on announced dates and new generations arrive with new ids. A blocked prompt returns no candidates at all, so candidates[0] throws a TypeError, and a response from the newer endpoint has no candidates field to begin with. The crash then appears far away from its cause, usually on a screen the user is looking at.

old-tutorial.js
const MODEL = "gemini-old-tutorial-id"; // copied from a blog post
const url =
  "https://generativelanguage.googleapis.com/v1beta/models/" + MODEL +
  ":generateContent?key=" + API_KEY; // key in the URL: proxies and logs record it
const res = await fetch(url, {
  method: "POST",
  body: JSON.stringify({ contents: [{ parts: [{ text: "Explain REST" }] }] }),
});
const data = await res.json();
console.log(data.candidates[0].content.parts[0].text); // TypeError when blocked

Why nothing in it is checked

Nothing in this snippet is checked against the contract. The id may no longer exist, the key sits in a URL that proxies and server logs record, and a safety block or an error body is treated as impossible. Reading the current docs, keeping the id in configuration and extracting text through one defensive function turns each of these into a handled case instead of a surprise.

Core concept: one family, two response shapes

Everything below comes from Google's own documentation for the Gemini API. Where a detail changes often, such as model ids, the lesson tells you where to look instead of printing a value that will go stale.

1. Two doors into the same API

Google's docs recommend the Interactions endpoint, POST https://generativelanguage.googleapis.com/v1beta/interactions, for new projects. They describe the generateContent endpoint as the older API that is still fully supported. Both authenticate with the same key header, so you can migrate one call at a time.

2. Auth and request body

Send the key in the x-goog-api-key header together with Content-Type: application/json. The body needs model and input, where input is a string for plain text. Optional fields include system_instruction, generation_config (for example max_output_tokens), tools and previous_interaction_id for continuing an earlier interaction. system_instruction, generation_config and tools apply only to the interaction being created, so repeat them on every turn.

3. An interaction is a list of steps

The reply is an Interaction resource with an id, a status and a chronological list of steps. A step of type model_output holds content parts, and a text part looks like { type: "text", text }. Other step types such as thought, function_call or google_search_call can appear as well, so select steps by type. The official SDKs expose interaction.output_text, which returns the last text blocks of the response.

4. Status and usage

status says whether the interaction is completed, failed, incomplete or still in progress, among other values. usage reports total_input_tokens, total_output_tokens, total_thought_tokens and total_tokens. Thinking tokens count toward the total, so a short answer can still use many tokens.

5. Errors carry codes, not just numbers

Every error is JSON shaped like { error: { code, message } } with a snake_case code. rate_limit_exceeded and too_many_requests mean slow down. quota_exceeded means the daily quota is gone, so retrying within minutes is pointless. authentication is a missing or bad key, and payment_required means prepaid credit ran out. A streaming request reports errors as an event whose event_type is error.

Model ids are configuration, not code

Take the id from Google's current models page, keep it in an environment variable and expect it to change. This lesson writes <model-id> on purpose, because any value printed here would age quickly.

Mental model: one extractor per shape
  1. Key travels in x-goog-api-key
  2. Body names model and input
  3. Pick the model_output step's text
  4. Error code decides retry or fix

Keep the knowledge of the response shape in exactly one function, so a future API revision changes one place and not every screen.

General pattern

bash
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "<model-id>",
    "input": "<prompt>"
  }'

Fill the two placeholders from the current docs. Illustrative only: run it with your own key in an environment variable, and note that some of Google's examples add a dated API-revision header, so copy whatever the current quickstart sends.

One extractor per response shape

The script starts a mock server with two endpoints: one answers in the Interactions shape and the other in the older generateContent shape, including a blocked-prompt reply. The client builds the request with the key header, extracts the text through one function per shape, prints the usage numbers, and then provokes a 401, a 400 and a 429 to show how the error code is read.

gemini-client.mjs
import http from "node:http";

const KEY = "demo-gemini-key";
const ANSWER = "REST lets programs talk over HTTP.";

// Mock server: one endpoint per response shape, no network and no real key.
let burstCalls = 0;
const server = http.createServer((req, res) => {
  let raw = "";
  req.on("data", (chunk) => (raw += chunk));
  req.on("end", () => {
    const send = (status, body) => {
      res.writeHead(status, { "content-type": "application/json" });
      res.end(JSON.stringify(body));
    };
    const fail = (status, code, message) => send(status, { error: { code, message } });

    if (req.headers["x-goog-api-key"] !== KEY) {
      return fail(401, "authentication", "The API key is missing or invalid");
    }
    const body = JSON.parse(raw);

    if (req.url === "/v1beta/interactions") {
      if (!body.model || typeof body.input !== "string") {
        return fail(400, "invalid_request", "model and input are required");
      }
      if (body.input === "burst" && burstCalls++ === 0) {
        return fail(429, "rate_limit_exceeded", "Too many requests per minute");
      }
      return send(200, {
        id: "interaction_demo",
        status: "completed",
        steps: [
          { type: "thought" },
          { type: "model_output", content: [{ type: "text", text: ANSWER }] },
        ],
        usage: {
          total_input_tokens: 7,
          total_output_tokens: 23,
          total_thought_tokens: 49,
          total_tokens: 79,
        },
      });
    }

    if (req.url === "/v1beta/models/mock-model:generateContent") {
      if (body.contents?.[0]?.parts?.[0]?.text === "blocked") {
        return send(200, { promptFeedback: { blockReason: "SAFETY" } });
      }
      return send(200, {
        candidates: [
          { content: { role: "model", parts: [{ text: ANSWER }] }, finishReason: "STOP" },
        ],
        usageMetadata: {
          promptTokenCount: 7,
          candidatesTokenCount: 23,
          totalTokenCount: 30,
        },
      });
    }
    fail(404, "not_found", "unknown path");
  });
});

async function post(base, path, key, body) {
  const res = await fetch(base + path, {
    method: "POST",
    headers: { "x-goog-api-key": key, "content-type": "application/json" },
    body: JSON.stringify(body),
  });
  const data = await res.json();
  if (!res.ok) {
    throw Object.assign(new Error(data.error.message), {
      status: res.status,
      code: data.error.code,
    });
  }
  return data;
}

// Interactions shape: the text sits in the model_output steps.
function interactionText(interaction) {
  return interaction.steps
    .filter((step) => step.type === "model_output")
    .flatMap((step) => step.content)
    .filter((part) => part.type === "text")
    .map((part) => part.text)
    .join("");
}

// generateContent shape: candidates may be missing when the prompt was blocked.
function legacyText(result) {
  const parts = result.candidates?.[0]?.content?.parts;
  if (!parts) return { blocked: result.promptFeedback?.blockReason ?? "no candidates" };
  return { text: parts.map((part) => part.text ?? "").join("") };
}

await new Promise((resolve) => server.listen(0, resolve));
const base = "http://127.0.0.1:" + server.address().port;

const ask = (input) => ({ model: "mock-model", input });
const interaction = await post(base, "/v1beta/interactions", KEY, ask("Explain REST"));
console.log("interactions:", interactionText(interaction));
console.log("steps:", interaction.steps.map((step) => step.type).join(", "));
const u = interaction.usage;
console.log("usage: in=" + u.total_input_tokens + " out=" + u.total_output_tokens +
  " thought=" + u.total_thought_tokens + " total=" + u.total_tokens);

const legacyPath = "/v1beta/models/mock-model:generateContent";
const asLegacy = (text) => ({ contents: [{ parts: [{ text }] }] });
const legacyOk = await post(base, legacyPath, KEY, asLegacy("Explain REST"));
console.log("legacy:", legacyText(legacyOk).text);
const legacyBlocked = await post(base, legacyPath, KEY, asLegacy("blocked"));
console.log("legacy blocked:", legacyText(legacyBlocked).blocked);

const failures = [
  ["bad key", "wrong-key", ask("hi")],
  ["no input", KEY, { model: "mock-model" }],
];
for (const [label, key, body] of failures) {
  try {
    await post(base, "/v1beta/interactions", key, body);
  } catch (err) {
    console.log(label + " ->", err.status, err.code);
  }
}

for (let attempt = 1; attempt <= 3; attempt++) {
  try {
    const burst = await post(base, "/v1beta/interactions", KEY, ask("burst"));
    console.log("burst ->", interactionText(burst));
    break;
  } catch (err) {
    console.log("burst -> retry after", err.status, err.code);
    await new Promise((resolve) => setTimeout(resolve, 2 ** attempt * 50));
  }
}
server.close();

Code breakdown

  1. Key in a headerheaders: { "x-goog-api-key": key, "content-type": "application/json" },

    The key travels in a header, never in the URL, so it stays out of access logs and browser history.

  2. Keep the error codecode: data.error.code,

    The thrown Error carries both the HTTP status and the snake_case code, because the code, not the number, says whether a retry makes sense.

  3. Pick steps by type.filter((step) => step.type === "model_output")

    The thought step in the mock has no text. Selecting model_output steps skips it, so the answer is read from the right place.

  4. Thought tokensu.total_thought_tokens

    The output shows 23 answer tokens but 49 thought tokens and a total of 79, which is why you should log the total, not only the answer length.

  5. Blocked prompt, no candidatesif (!parts) return { blocked: result.promptFeedback?.blockReason ?? "no candidates" };

    For generateContent the optional chain avoids the TypeError and the function reports why nothing came back instead.

  6. Backoff before a retryawait new Promise((resolve) => setTimeout(resolve, 2 ** attempt * 50));

    After rate_limit_exceeded the loop waits 100 ms, then 200 ms, and gives up after three attempts. The mock lets the second try through.

You should see
interactions: REST lets programs talk over HTTP.
steps: thought, model_output
usage: in=7 out=23 thought=49 total=79
legacy: REST lets programs talk over HTTP.
legacy blocked: SAFETY
bad key -> 401 authentication
no input -> 400 invalid_request
burst -> retry after 429 rate_limit_exceeded
burst -> REST lets programs talk over HTTP.

The same call in curl, and the older shape

The first command below is the Interactions call; the second is the older generateContent call. Both are illustrative: check the current docs, put your own key in GEMINI_API_KEY, and replace <model-id> with an id from the models page.

bash
# Illustrative - check the current docs, and use your own key in GEMINI_API_KEY.
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "<model-id>",
    "input": "Explain REST in one short paragraph."
  }'
bash
# Older shape, still seen in tutorials. Illustrative - check the current docs.
curl -X POST \
  "https://generativelanguage.googleapis.com/v1beta/models/<model-id>:generateContent" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"contents": [{"parts": [{"text": "Explain REST in one short paragraph."}]}]}'
InteractionsgenerateContent (older)
Input fieldinputcontents[].parts[].text
Text lives insteps[] of type model_outputcandidates[0].content.parts[]
Token usageusage.total_*_tokensusageMetadata.*TokenCount
Blocked promptan error code such as safetypromptFeedback.blockReason

Error codes worth handling

Google's error table maps each snake_case code to an HTTP status and a recommended action. The rows you meet first are below. Two codes, safety and recitation, are listed separately as generation-blocked codes without an HTTP status, so a robust client handles both an error body and a reply that has no text.

Code (HTTP)MeaningClient action
rate_limit_exceeded (429)Per-minute or per-second limit hitRetry with backoff
quota_exceeded (429)Daily quota used upWait for reset or ask for more
service_unavailable (503)Overloaded or downRetry with backoff
invalid_request (400)Malformed requestFix the request
authentication (401)Key missing or invalidFix the key
payment_required (402)Prepaid credit used upStop until credit is added

Key safety and cost

Put the key in an environment variable on your own back end and let the browser call that back end. Limits and prices are set by Google per model and plan, so read the current pages instead of memorising numbers. Cap output with generation_config, log usage on every call, and remember that thought tokens appear in the total.

In real projects

How to apply it in a real project

Imagine a nightly job that summarises customer feedback. Wrap Gemini in a small server-side adapter: the model id comes from an environment variable, one function turns whichever response shape you receive into { text, usage }, and a classifier turns each error code into retry, wait, fix or stop. A timeout created with AbortSignal.timeout stops a stuck request from freezing the whole job.

Test the adapter with a mock server that plays success, a blocked output, rate_limit_exceeded, quota_exceeded, authentication and a timeout. When Google retires the model you chose, the migration is a one-line configuration change plus a green test run against a staging key. Keep a short runbook note with the id in use, the date you last verified it and the person who owns the key.

Common mistakes

Common mistakes

Gemini integrations most often break in these four ways.

Hard-coding a model id from a tutorial

Ids are retired or re-routed on published dates. A copied id can start returning not_found one day, or quietly point at a model that behaves differently. Keep it in configuration and re-check the models page when you ship.

Assuming candidates[0] always exists

With generateContent a blocked prompt returns HTTP 200 with promptFeedback.blockReason and no candidates, and the Interactions shape has no candidates field at all. Read text through an extractor that handles a missing path.

Retrying quota_exceeded like a rate limit

Both arrive as 429, but rate_limit_exceeded clears in seconds while quota_exceeded means the daily quota is gone. Looping on it only burns attempts and time; wait for the reset or ask for more quota.

Putting the key in a URL or in browser code

URLs are written to server logs, proxy logs and browser history, and anything in browser code is public. Use the header, and call from your own back end.

Best practices

Habits worth keeping

  • Read the quickstart and the error page of the API revision you target, and note the date you did.
  • Log the interaction status and usage on every call, so cost surprises show up in your own dashboards first.
  • Add a contract test that feeds each response shape and each error code to your extractor.

Mini challenge

Classify the error codes

Write classify(code), which sorts Gemini error codes into four actions: retry, wait, fix and stop, with log for any code you do not know yet. Then prove it: start a mock server on port 0 that fails with the code you ask for, call it once per code with fetch, and print the HTTP status, the code and the chosen action on one line.

  • Treat quota_exceeded differently from rate_limit_exceeded
  • Never retry payment_required
  • Return log for unknown codes instead of throwing
  • Read the code from error.code in the JSON body, not from the HTTP status alone
classify.mjs
import http from "node:http";

// TODO 1: decide what a caller should do for each error code and group the codes:
//   retry - wait with exponential backoff, then try again
//   wait  - the daily quota is used up: do not hammer, wait for the reset
//   fix   - the request or the credentials are wrong: change them first
//   stop  - money is the problem: never retry
// Codes to place: rate_limit_exceeded, too_many_requests, service_unavailable,
// api_error, quota_exceeded, invalid_request, parameter_unknown, authentication,
// permission_denied, payment_required

function classify(code) {
  // TODO 2: return the group name, or "log" for a code you do not know yet
  return "log";
}

// TODO 3: start a mock server on port 0. It reads { input } from the JSON body and
//   answers with an HTTP error whose body is { error: { code: input, message } }.
//   Pick a realistic status for each code (429, 503, 400, 401, 402, 500 ...).

// TODO 4: POST every code with fetch, read error.code from the reply, and print
//   one line per code, for example:  429 quota_exceeded -> wait

// TODO 5: close the server

Expected: Seven lines such as "429 quota_exceeded -> wait", with rate and 503 codes marked retry, request and key problems marked fix, payment_required marked stop and the invented code marked log.

Show hint

Keep the groups in one object of arrays and loop over Object.entries(). An unknown code falls out of the loop and returns "log".

Show solution
classify.mjs
import http from "node:http";

// What a caller should do for each documented error code.
const GROUPS = {
  retry: ["rate_limit_exceeded", "too_many_requests", "service_unavailable", "api_error"],
  wait: ["quota_exceeded"],
  fix: ["invalid_request", "parameter_unknown", "authentication", "permission_denied"],
  stop: ["payment_required"],
};
function classify(code) {
  for (const [action, codes] of Object.entries(GROUPS)) {
    if (codes.includes(code)) return action;
  }
  return "log";
}

// Mock server: fails with whatever code the request asks for.
const STATUS = {
  rate_limit_exceeded: 429,
  quota_exceeded: 429,
  service_unavailable: 503,
  invalid_request: 400,
  authentication: 401,
  payment_required: 402,
  brand_new_code: 500,
};
const server = http.createServer((req, res) => {
  let raw = "";
  req.on("data", (chunk) => (raw += chunk));
  req.on("end", () => {
    const { input } = JSON.parse(raw);
    res.writeHead(STATUS[input], { "content-type": "application/json" });
    res.end(JSON.stringify({ error: { code: input, message: "demo failure" } }));
  });
});
await new Promise((resolve) => server.listen(0, resolve));

const url = "http://127.0.0.1:" + server.address().port + "/v1beta/interactions";
for (const code of Object.keys(STATUS)) {
  const res = await fetch(url, { method: "POST", body: JSON.stringify({ input: code }) });
  const { error } = await res.json();
  console.log(res.status, error.code, "->", classify(error.code));
}
server.close();

Quick quiz 1 / 3

Where does the answer text live in a response from the Interactions endpoint?

Quick quiz 2 / 3

A call fails with HTTP 429 and error.code quota_exceeded. What should the client do?

Quick quiz 3 / 3

A generateContent call returns HTTP 200 with promptFeedback.blockReason set to SAFETY. What does result.candidates[0] do?

What to remember

  • The Interactions endpoint takes a model and an input, authenticates with x-goog-api-key and returns steps; the older generateContent shape still exists in many tutorials.
  • Select text from model_output steps, and guard the older candidates path against blocked prompts.
  • Thought tokens count toward usage, so log total_tokens and not only the answer length.
  • Read error.code to decide: retry rate limits, wait out quota_exceeded, fix 400 and 401, stop on payment_required.

Gemini API Documentation — Google

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Gemini (Google AI) API | Thuta Learning