Calling Gemini from Google Apps Script

📘 Lesson 5 — Calling Gemini from Google Apps Script (Text Prompts → AI Responses)

Blog Post #5 in the Apps Script + APIs + Gemini Series

Up to this point, you’ve learned how to:

  • Call APIs
  • Parse JSON
  • Build web apps
  • Secure API keys properly

Now it’s time to bring AI into your Apps Script projects.

In this lesson, you’ll learn how to call Google’s Gemini API directly from Google Apps Script, send it prompts, and safely extract useful responses.

This is the foundation for:

  • AI assistants
  • Document summarizers
  • Sheet explainers
  • Gemini-powered dashboards
  • Custom learning tools

🎯 What You’ll Learn

By the end of this lesson, you’ll be able to:

✅ Call Gemini using the REST API
✅ Send text prompts from Apps Script
✅ Parse Gemini’s structured JSON response
✅ Handle errors safely
✅ Build a reusable Gemini helper function
✅ Understand how prompts turn into AI output


🧠 How Gemini Works (Conceptually)

Gemini does not read English the way humans do.

At a high level:

  1. Your prompt text is converted into embeddings
  2. Those embeddings are compared inside a vector space
  3. Gemini predicts the most likely next tokens
  4. The response is returned as structured JSON

Apps Script doesn’t care about that complexity — it just sends JSON and receives JSON.


📍 Step 1 — Prerequisites (Important)

Before continuing, make sure you have:

✅ Completed Lesson 4
✅ Stored your API key in Script Properties
✅ Added a property named:

GEMINI_API_KEY

⚠️ Do NOT hard-code your key.


📍 Step 2 — Gemini REST Endpoint

We’ll use the generateContent endpoint:

POST
https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent

Authentication is handled via the API key.


📍 Step 3 — Reusable Gemini Helper Function

This is the core function you’ll reuse everywhere.

/**
 * Send a text prompt to Gemini and return the AI response.
 */
function callGemini(prompt) {
  if (!prompt) {
    throw new Error('Prompt is required');
  }

  // Get API key securely
  var apiKey = getApiKey('GEMINI_API_KEY');

  // Gemini endpoint
  var url =
    'https://generativelanguage.googleapis.com/v1beta/models/' +
    'gemini-1.5-flash:generateContent?key=' +
    encodeURIComponent(apiKey);

  // Request payload
  var payload = {
    contents: [
      {
        parts: [
          { text: prompt }
        ]
      }
    ]
  };

  var options = {
    method: 'post',
    contentType: 'application/json',
    payload: JSON.stringify(payload),
    muteHttpExceptions: true
  };

  // Call Gemini
  var response = UrlFetchApp.fetch(url, options);
  var status = response.getResponseCode();
  var rawText = response.getContentText();

  if (status !== 200) {
    Logger.log(rawText);
    throw new Error('Gemini API error: ' + status);
  }

  var data = JSON.parse(rawText);

  // Safely extract AI text
  var output =
    data.candidates &&
    data.candidates[0] &&
    data.candidates[0].content &&
    data.candidates[0].content.parts &&
    data.candidates[0].content.parts[0] &&
    data.candidates[0].content.parts[0].text;

  return output || 'No response returned';
}

🔍 Breaking Down the Code

Prompt Input

function callGemini(prompt)

The function accepts plain text — this keeps it flexible.


Payload Structure

contents → parts → text

Gemini expects structured content, even for simple prompts.


Error Handling

  • HTTP status is checked
  • Raw response is logged if something fails
  • The function fails loudly (important for debugging)

Response Parsing

Gemini responses are nested.

We never assume values exist — we safely traverse the object.


📍 Step 4 — Test Gemini with a Simple Prompt

Add this test function:

function testGemini() {
  var prompt = 'Explain APIs in simple terms for beginners.';
  var result = callGemini(prompt);
  Logger.log(result);
}

Run it and open View → Logs.

🎉 You just successfully called Gemini from Apps Script.


📍 Step 5 — Practical Prompt Examples

Try swapping the prompt with:

'Summarize the benefits of automation in one paragraph.'
'Explain JSON to a 12-year-old.'
'Give me three ideas for a Google Sheets automation.'

This shows how prompt design controls output.


🧪 Exercises (Very Important)

Exercise 1 — Prompt Variations

Create a function that sends:

  • Short prompt
  • Long detailed prompt
    Compare the responses.

Exercise 2 — Defensive Coding

Modify callGemini() to return:

"Gemini did not return text"

if the response structure changes.


Exercise 3 — Prompt Templates

Create a helper:

function explainConcept(concept) {
  return callGemini(
    'Explain "' + concept + '" in simple terms with examples.'
  );
}

Test with different concepts.


💡 Pro Tips for Gemini in Apps Script

Tip 1 — Keep Prompts Explicit

“Explain X for beginners in 3 bullet points” works better than vague prompts.


Tip 2 — Gemini Is Stateless

Every request is independent — include all context in the prompt.


Tip 3 — Treat Gemini as a Function

Input → Output
No magic. Just structured text processing.


🔮 What’s Next?

In Lesson 6, you’ll use Gemini inside Google Sheets:

Lesson 6 — Gemini-Powered Google Sheets Tools

  • Custom menus
  • Selected range → AI explanation
  • Writing AI output back into cells
  • Real productivity workflows