How to Use the Gemini API: Setup and First Request

Updated:

You have a task Gemini could handle, but getting it into your workflow means dealing with API keys, model names, packages, and billing settings. A prompt that works in a chat window doesn’t tell you how to connect the same task to your application.

A failed request can leave you guessing whether the key, code, or billing is at fault. We’ll work through a complete JavaScript example and send the same request over HTTP, so you can test a product-description task locally and move it into an automation tool.

Create Your Gemini API Key

Google AI Studio lets you test prompts and manage API keys. The Gemini Developer API lets your application send those prompts programmatically.

You must be at least 18 and access the service from a supported region. Google lists these requirements on its availability page.

Create Your Gemini Api Key: Gemini Api Keys: Projects And Replacement; Every Key Belongs To A Project; Billing; Permissions; Quota; Exposed Key? Replace It; 1. Create Replacement; 2. Update Application; 3. Revoke Old Key; Deleting A File Does Not

To get your key:

  1. Sign in to the Google AI Studio API keys page.
  2. Accept the terms if prompted.
  3. Copy the default key, or select Create API key and choose a project.
  4. If you need an existing Google Cloud project that isn’t listed, import it into AI Studio first.

Each key belongs to a Google Cloud project, which groups its billing, permissions, and usage limits (quota). Note the project you chose because you’ll check its billing status before testing.

Keep the key outside your script. Don’t put it in browser code, a public repository, screenshots, or shared workflow exports. Browser code is visible to visitors, even when the page itself requires a login.

If a key is exposed, create a replacement, update your application, and revoke the old key. Removing it from a file doesn’t disable it.

For this walkthrough, imagine your shop sells printable meal-planning templates. You want Gemini to turn a short list of product features into a description draft.

Choose a Model for Your First Request

Start With Gemini 3.8 Flash

Choose a model that accepts your input and produces the output you need. Then compare the quality, response time, and cost.

We need text in and text out, so I would start with Gemini 3.8 Flash. Its exact model identifier is:

gemini-3.8-flash
Start With Gemini 3.8 Flash: Choose A Gemini Model For Product Descriptions; Text Input; Text Output; Keep One Model While Debugging; Gemini-3.8-Flash; Get The Request Working; Then Compare; Quality; Response Time; Cost

Google lists this as a stable model with text output. It fits our product-description task, and we’ll use that identifier in both examples. See the model specifications if your task also needs images, audio, or other inputs.

I would skip model comparisons until this request works. Changing models while debugging authentication adds another moving part.

Check Free Access and Pricing

Check the project’s billing tier in AI Studio before running the script. Gemini 3.8 Flash offers free input and output tokens on the Free Tier, within its usage limits. Projects on paid tiers use the paid rates below. Additional projects and projects imported from Google Cloud may need verification before receiving free access.

Tokens are small units of content the model reads or generates. Your prompt uses input tokens. Billable output includes both the answer and thinking tokens used for the model’s internal reasoning.

Check Free Access And Pricing: Check Gemini Api Access Before Testing; Check Your Project'S Billing Tier; Free Access; Check Model Availability And Limits; Verification May Be Required; Paid Access; Link A Billing Account; If Your Account Uses

For regular paid text requests, under Google’s Standard pricing, the rates are:

UsageThrough December 31, 2026Starting January 1, 2027
Input, per million tokens$0.75$1.50
Output, including thinking, per million tokens$3.75$7.50

Check the official pricing page before estimating a larger workload.

Check Free Access And Pricing: Estimate Gemini Api Tokens Before Cost; 100 Descriptions; Illustrative Workload; 1,000 Input Tokens Each; 100 × 1,000 = 100,000; 200 Billable Output Tokens Each; Answer + Thinking; 100 × 200 = 20,000; Tokens ÷

Suppose 100 descriptions each use 1,000 input tokens and 200 billable output tokens, including thinking. That totals 100,000 input tokens and 20,000 billable output tokens. At the table’s rates through December 31, 2026:

Input:  100,000 ÷ 1,000,000 × $0.75 = $0.075
Output:  20,000 ÷ 1,000,000 × $3.75 = $0.075
Total: $0.15

That assumes Standard paid requests without tools, caching, or retries. It’s an example calculation, not a prediction of your token usage.

Paid access requires linking a billing account. If your account uses Prepay, you must buy at least $5 in credits, or the currency equivalent, before making paid requests. Check the billing arrangement offered before enabling paid usage.

Install the JavaScript SDK

Prepare a Node.Js Project

The SDK is Google’s JavaScript package for calling the API. Install Node.js 22 or newer, then open a terminal and check your version:

node --version

Create a folder for the example and install the package:

mkdir gemini-first-request
cd gemini-first-request
npm init -y
npm install @google/genai

These prerequisites and the package name come from Google’s JavaScript SDK documentation.

Create a file named first-request.mjs inside this folder. The .mjs extension lets Node use the imports and top-level await in our example.

Run this code locally or on a backend server. A JavaScript example doesn’t need to run in a browser.

Load the API Key Securely

Set the key in the terminal where you’ll run the script. Replace YOUR_API_KEY with your actual key.

For Bash or Zsh:

export GEMINI_API_KEY="YOUR_API_KEY"

For Windows PowerShell:

$env:GEMINI_API_KEY="YOUR_API_KEY"
Load The Api Key Securely: How Gemini Api Keys Reach Your Script; Set The Key In This Terminal; Gemini_Api_Key; The Launched Script Reads It; Process.env.gemini_Api_Key; No Key Pasted Into Source; New Terminal? Set It Again; Deployment: Use Secret

These settings apply to the current terminal session. If you open another terminal, set the variable there too.

The script will read process.env.GEMINI_API_KEY, check that it exists, and pass it to the SDK. You won’t need to paste the key into the file or print it to check authentication.

When you deploy the workflow later, add the variable to your server’s secret settings or your automation tool’s credential storage.

Send Your First Gemini API Request

Build the Request

We’ll use the Interactions API, which Google recommends for new projects. Existing generateContent integrations remain supported, but their request fields and response helpers differ. Keep the examples separate when following other tutorials. See Google’s Interactions API overview.

The request has four main parts:

  • Authentication: The client receives your API key.
  • Model: model selects Gemini 3.8 Flash.
  • Task: input contains your instructions and product details.
  • Generation Settings: generation_config controls thinking level and output length.

Use the supplied meal-planner details for this test. Under Google’s Gemini API terms, don’t submit sensitive, confidential, or personal information to unpaid services. If you’re in the European Economic Area (EEA), Switzerland, or the UK, paid-service data-use terms apply even to free usage. If you make an application available to users in those regions, you must use Paid Services.

Build The Request: Four Parts Of A Gemini Interactions Request; 1. Authentication; Apikey; 2. Model; Gemini-3.8-Flash; 3. Task; Input; Two Sentences; Supplied Facts Only; 4. Generation Settings; Thinking_Level: Low; Max_Output_Tokens: 1000

Paste this complete example into first-request.mjs:

import { GoogleGenAI } from "@google/genai";

const apiKey = process.env.GEMINI_API_KEY;

if (!apiKey?.trim()) {
  console.error(
    "Missing GEMINI_API_KEY. Set it in this terminal, then run again."
  );
  process.exit(1);
}

const ai = new GoogleGenAI({ apiKey });

try {
  const interaction = await ai.interactions.create({
    model: "gemini-3.8-flash",
    input:
      "Write a two-sentence product description using only these details: " +
      "printable weekly meal planner; seven-day layout; shopping-list section. " +
      "Do not add features.",
    generation_config: {
      thinking_level: "low",
      max_output_tokens: 1000,
    },
  });

  const text = interaction.output_text?.trim();

  if (interaction.status === "completed" && text) {
    console.log(text);
  } else {
    console.error("Gemini returned no completed, usable text.", {
      status: interaction.status,
      errors: interaction.errors ?? [],
      stepTypes: interaction.steps?.map((step) => step.type) ?? [],
    });
    process.exitCode = 1;
  }
} catch (error) {
  console.error(
    "Gemini request failed:",
    error instanceof Error ? error.message : String(error)
  );
  process.exitCode = 1;
}

The prompt gives the model a narrow task and the facts it may use. That makes the result easier to check than a loose instruction such as “write compelling product copy.”

The low thinking level is my starting choice for this simple task. The 1,000-token allowance limits generation length; it doesn’t set a monetary budget or require the model to use the whole allowance.

Run the Script and Check the Result

From the project folder, in the terminal containing your key, run:

node first-request.mjs

A completed interaction with nonempty text confirms that authentication, model selection, and generation worked.

For illustration, the output could look like this:

Plan your week with a printable meal planner featuring a seven-day layout. Keep your shopping list alongside your meal plans with the included shopping-list section.

Run The Script And Check The Result: Check Gemini Product Descriptions Before Use; First: Confirm Usable Output; Status: Completed; Nonempty Text; Match These Supplied Facts; Printable Weekly Planner; Seven-Day Layout; Shopping-List Section; Reject

That is sample wording, not output captured from an authenticated run.

Now compare the response with the supplied features. It should describe a printable weekly planner, a seven-day layout, and a shopping-list section. It shouldn’t promise editable files, recipes, or automatic shopping lists.

If usable text is missing, inspect the reported status and errors array. The returned steps can show what happened during generation. An incomplete status can mean the model reached its output allowance, so inspect the response before increasing that limit.

Call the Gemini API Directly With HTTP

An automation tool can send the same request without installing the JavaScript SDK. It needs an HTTP step that accepts a method, URL, headers, and JSON body.

Use POST with this endpoint:

https://generativelanguage.googleapis.com/v1beta/interactions

The URL selects the operation, and the JSON body supplies the model and task. This follows Google’s REST request pattern.

Here is the complete request using curl, a command-line tool for sending HTTP requests. Run it in Bash with the same environment variable as the JavaScript script:

curl --request POST \
  "https://generativelanguage.googleapis.com/v1beta/interactions" \
  --header "x-goog-api-key: $GEMINI_API_KEY" \
  --header "Content-Type: application/json" \
  --header "Api-Revision: 2026-05-20" \
  --data '{
    "model": "gemini-3.8-flash",
    "input": "Write a two-sentence product description using only these details: printable weekly meal planner; seven-day layout; shopping-list section. Do not add features.",
    "generation_config": {
      "thinking_level": "low",
      "max_output_tokens": 1000
    }
  }'
Call The Gemini Api Directly With Http: Extract Gemini Text From An Http Response; Require Status: Completed; Inspect Response; 1. Read Steps[]; 2. Keep Type: Model_Output; 3. In Content[], Keep Type: Text; 4. Join Text Values; Confirm Nonempty

Make and n8n let you connect apps in a visual workflow. I would use Make for a quick setup or n8n when I need more control over the surrounding logic.

Store the key in the tool’s credential facility and use it for the x-goog-api-key header. Copy the method, URL, other headers, and JSON body into the HTTP step. Keep the key out of fields that appear in shared exports.

The raw response needs one extra step. Check that status is completed, then:

  1. Read the steps array.
  2. Select entries where type is model_output.
  3. Read their content arrays and collect entries where type is text.
  4. Join their text values and confirm the result isn’t empty.

The SDK’s output_text property is a convenience helper, so don’t expect that field in raw HTTP JSON. Google documents the status and step fields in the Interaction response reference.

Fix Common First-request Errors

Read the error code and message before changing settings. The same HTTP status can cover problems that need different fixes.

Symptom or StatusLikely CauseNext Action
Local missing-key message or 401Key missing or invalidSet the variable in the running terminal and verify the key.
400Invalid JSON, parameters, or unmet prerequisitesCorrect the request; follow any failed_precondition message.
402Prepay credits depletedAdd credits before retrying.
403Permissions or project restrictionsCheck access, verification, and billing.
404Wrong model or resource pathCheck the exact model ID, endpoint, and API version.
429 with rate_limit_exceeded or too_many_requestsTemporary request or token limitSlow down and retry with increasing delays.
429 with quota_exceededDaily quota exhaustedWait for reset or request more quota.
503Temporary service failureRetry with bounded delays.
Import or missing-method errorPackage missing or outdatedRun inside the project folder and update the SDK.
Fix Common First-Request Errors: Gemini Api Errors: Retry, Wait, Or Add Credits?; Read The Code And Message; 429: Rate_Limit_Exceeded; Or Too_Many_Requests; 503: Temporary Failure; Retry With Bounded Delays; 429: Quota_Exceeded; Wait For Reset Or

The HTTP distinctions above follow Google’s API error reference.

For package problems, run these commands inside your project folder:

npm ls @google/genai
npm install @google/genai@latest

JavaScript Interactions support requires version 2.3.0 or later.

For temporary failures, use increasing retry delays, add a small random delay, and stop after a fixed number of attempts. Check the SDK’s existing retry behavior before adding another loop. Two retry systems can multiply requests faster than you intended.

Connect the Working Request to Your Workflow

Once the fixed request works, replace the hardcoded features with validated product-record fields.

Keep the first workflow simple:

Product record → Gemini draft → Review → Saved description

For the meal-planning shop, confirm that the product record contains its name, format, and actual features before sending it. Save the returned description as a draft and compare its claims with those fields.

Replacing the sample prompt is easier when the surrounding validation and failure handling are drafted too. The AI API Integration Studio below builds those pieces around your task and a fictional input record.

Lead Magnet Cover
FREE AI SKILL

Free AI API Integration Studio

Use AI to turn a working API request into code or an HTTP setup for your workflow.
Send My AI API Integration Studio ❯
Instantly delivered to your inbox
Customer Avatar 1
Customer Avatar 2
Customer Avatar 3
Customer Avatar 4
Rated highly by 2,500+ users

In one of my digital-product workflows, a product-copy draft called a fixed PDF “customizable.” The sentence sounded useful, but the feature didn’t exist. I tightened the instructions and kept the approval step because polished wording isn’t proof.

Connect The Working Request To Your Workflow: Build A Reviewed Gemini Product-Copy Workflow; Validate Product Record; Name • Format • Actual Features; Generate Draft; Failed Request → Inspect; Review Every Feature Claim; Invented Feature → Revise

For your planner descriptions, reject invented features and route failed requests for inspection. Record the product ID, request status, response time, and token usage without logging secrets.

Before processing a batch, add a few controls:

  • Timeout: Stop waiting after a defined period and flag the record for review.
  • Call Limit: Set a maximum number of automated calls, including retries.
  • Concurrency: Limit how many requests run at once.
  • Duplicate Protection: Mark completed records so rerunning the workflow doesn’t regenerate every description.

Start with a handful of products and review both the drafts and usage before expanding the batch.

Also check the model’s active requests-per-minute, input-tokens-per-minute, and requests-per-day limits in AI Studio. Quotas apply per project, so creating another key in the same project won’t increase them. Daily request quotas reset at midnight Pacific time, according to Google’s rate-limit rules.

For a self-service billing account, set a project spend cap and check whether Prepay is set to buy more credits automatically. Google’s billing guide warns that caps are experimental and billing can lag by around ten minutes, allowing overages. Keep your application’s call limits even after setting a cap.

I would expand the workflow only after a small batch produces useful drafts at an acceptable cost. A successful API response is the starting point. The review and failure paths make it useful in a business.

What Next?

Create your API key and run first-request.mjs with the supplied fictional product details. Check the description against those three features before replacing them with your own product data.

Use the social buttons to share this walkthrough when your next automation discussion gets stuck at “how do we connect the API?”

Which repeated task would you connect to Gemini first, and what would you need to check before trusting its output? Leave your answer—or any setup questions—in the comments.

Share this post with your friends & followers:
Abhishek is a data scientist by day & an online entrepreneur by night. He is known for his ability to simplify complex concepts and make them accessible to a wider audience. He started Passive Book to share his insights and experiences on how to effectively build an online business, which has quickly become a go-to resource for anyone looking to bootstrap an online business from scratch.

Leave a Comment

Build an Online Business 
Without Quitting Your Job

Join 10,000+ solopreneurs building six-figure online businesses from scratch with limited time & tight budgets using smart systems & AI automations.
Optin Form - Main

Free Bonus: Get access to our AI workflows & cheat sheets
Person sitting with laptop in home office environment with launching rocket, coffee mug, sleeping dog, bookshelf, and house plant illustrating work-from-home online business lifestyle. Decorative image.
Thank you for sharing

Follow Us On: