Lompat ke konten

Pelajaran 17 ยท The Gemini API

Your First Gemini API Request

Make your first Gemini API call with the Interactions API in Python, JavaScript and cURL, create and protect an API key, and read the response.

The Gemini API lets your program send input to a Gemini model and use the reply. This chapter shows the main ideas with real code. This site cannot run those calls, so real API code is read-only, and runnable blocks are labeled stand-ins or plain helpers.

As of December 2026, Google's documentation presents the Interactions API as the recommended way to build with Gemini. The older generateContent API is still supported but is described as legacy. You will see it in many older articles, so check which one a code sample uses.

Get an API key

You create and view keys on the API keys page of Google AI Studio. Google's documentation says new keys made there are authorization keys tied to a service account. Treat any key like a password:

  • Store it in an environment variable, GEMINI_API_KEY.
  • Never commit it to version control.
  • Never put it in browser or mobile app code. Call the API through your own server.
  • If it leaks, create a new key, switch your app to it, disable the old one and check your usage.

The libraries also read GOOGLE_API_KEY. If both variables are set, Google's documentation says GOOGLE_API_KEY takes priority. That can explain a confusing "wrong key" problem.

Terminal
# Read-only. macOS or Linux shell. On Windows, use Environment Variables.
export GEMINI_API_KEY="paste-your-key-here"

Install the SDK and send a request

The official Python package is google-genai:

Terminal
pip install -U google-genai
Python
# Read-only: needs the SDK, a key and network access.
from google import genai

client = genai.Client()   # reads the key from the environment

interaction = client.interactions.create(
    model="gemini-4-hydrogen",
    system_instruction="You are a friendly tutor. Use plain English.",
    input="Explain what an API is in three sentences.",
)
print(interaction.output_text)

In JavaScript, the package is @google/genai (npm install @google/genai):

JavaScript
// Read-only: run this on a server, never in public browser code.
import { GoogleGenAI } from "@google/genai";

const ai = new GoogleGenAI({}); // reads the key from the environment

const interaction = await ai.interactions.create({
  model: "gemini-4-hydrogen",
  input: "Explain what an API is in three sentences.",
});
console.log(interaction.output_text);

The REST form shows what travels over the network. Google's quickstart also sends an Api-Revision header that selects an API revision. Copy the current value from the official page.

Terminal
# Read-only.
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Api-Revision: 2026-05-20" \
  -d '{"model": "gemini-4-hydrogen", "input": "Say hello in two words."}'

What comes back

An interaction has an id and a list of steps in order. Steps can include the model's thoughts, tool calls, tool results and the model output. The SDKs give you the final text as output_text. In a raw REST response, you find the text inside the step whose type is model_output.

The stand-in below builds a response with that general shape and reads the text from it. The data is invented, and real responses contain more fields.

Python Stand-in: read text from a response with steps

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Models

Some model IDs on Google's model list as of December 2026:

ID Notes from Google's pages
gemini-4-carbon Most capable reasoning; no free tier
gemini-4-neon Frontier intelligence for complex workflows; no free tier
gemini-4-hydrogen Fast, for everyday coding and agent work; has a free tier
gemini-3.8-flash A stable Flash model; has a free tier
gemini-3.5-flash-lite A stable, lighter model; has a free tier

The list also has other models, including ones for images, video, speech, live voice and embeddings. Several older models are deprecated or shut down, so check the official list before you copy a model name from anywhere. Keep the model name in your configuration instead of repeating it through your code.

Check input before you send it

Even before you write the real call, decide how your program handles empty or very large input:

Python Stand-in: a request wrapper with input checks

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Passing the sending function as an argument lets you test your program without calling the real API. That saves money and makes tests repeatable.

If your first call fails

Work through the likely causes in order:

  1. Import error: confirm that you installed google-genai in the same Python environment that runs your script.
  2. Missing key: check that the variable is set in the terminal or service that runs the program. A new terminal may be needed after you change system variables.
  3. Wrong key: check whether GOOGLE_API_KEY is also set, because it takes priority.
  4. Unknown model: compare the ID, character by character, with the official model list.
  5. Permission or limit errors: read the full error message and check the project in AI Studio.

Do not paste your key into a chat or a public forum when you ask for help. Share the error text only after you remove keys, project details and any private input. The lesson on errors and limits explains status codes.

Keep configuration apart from code

Read settings such as the model name and a request size limit from one configuration place, with a sensible default. Then you can change the model in a test setup without editing every call, and you can rerun your tests before the change reaches users. When you switch models, check settings too, because supported options can differ between models.

Common mistake: pasting your key into a script to "test quickly" and then committing or sharing the file. Use an environment variable from the very first line.

Check your understanding

Quick check ยท 3 questions

of 3 answered You scored / 3 ยท perfect!

  1. 1. Which API does Google's documentation recommend for new work, as of December 2026?

    generateContent still works but is described as legacy.
  2. 2. Where should the API key be kept for local development?

    Environment variables keep keys out of your files and repository.
  3. 3. In a raw REST response, where is the reply text?

    The SDKs also expose it as output_text for convenience.

Summary

  • Use the Interactions API with the google-genai or @google/genai SDK.
  • Keep keys in environment variables and away from client code.
  • A response is a sequence of steps, and output_text gives the final text.
  • Check model IDs on the official list.

Next: Conversations, Thinking and Streaming

Progres Anda disimpan di browser ini. Tidak perlu akun.