DEV Community

Tanaike for Google Developer Experts

Posted on

Seamless Integration of Google Workspace and Gemini API via External URLs

fig1

Abstract

The Gemini API now supports external file URLs, allowing developers to process data directly without uploading it first. This article demonstrates how to leverage this update to integrate Google Workspace resources—including Google Sheets, Docs, Slides, and Apps Script—into Gemini’s workflow, covering both public and secure private access methods.

Introduction

Recently, the limitations regarding inline file data in the Gemini API have been significantly updated Ref. The maximum file size has increased from 20 MB to 100 MB. Furthermore, external file URLs—both public and signed—can now be used directly as input.

The ability to use public external file URLs is particularly significant. Previously, data had to be uploaded to Gemini's servers first to generate an internal URI for processing. Eliminating this step substantially reduces processing overhead and latency.

It is considered that this update effectively bridges the gap between the Gemini API and the Google Workspace ecosystem. This article investigates the technical specifications of these external file URLs and explores how they enhance interoperability with Google Sheets, Docs, Slides, and Google Apps Script.

Prerequisites

To test the samples provided in this article, you will need a valid Gemini API Key.
Get an API Key here.

Integration with Google Workspace Files (Sheets, Docs, Slides)

Google Sheets is a representative resource within Google Workspace. In this section, we demonstrate how to use Google Sheets (and by extension, Docs and Slides) as an external URL source for the Gemini API.

1. Setting up the Google Sheet

Please create a new Google Spreadsheet and populate it with sample data. The image below shows the sample table used in this demonstration.

fig2

For the initial test, share this Google Spreadsheet publicly as "Anyone with the link can view". Ref Copy the Spreadsheet ID from the URL bar.

2. Client Script for Public URLs

Here, Node.js is used as the client environment. Ref

Please replace ### with your actual Spreadsheet ID in the spreadsheetId variable.

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

const spreadsheetId = "###";
const ai = new GoogleGenAI({});

async function main() {
  // Construct the URL to export the Sheet as a PDF
  const uri = `https://docs.google.com/spreadsheets/d/${spreadsheetId}/export?format=pdf`;

  const response = await ai.models.generateContent({
    model: "gemini-3-flash-preview",
    contents: [
      createPartFromUri(uri, "application/pdf"),
      "Describe the PDF data.",
    ],
  });
  console.log(response.text);
}

main();
Enter fullscreen mode Exit fullscreen mode

When this script is executed, the Gemini API directly accesses the PDF export URL of the Spreadsheet. The result confirms that the model can interpret the current state of the Spreadsheet:

The PDF contains a table for tracking customer feedback, including manual input and AI-generated analysis. The table consists of five columns: **Date**, **Purchase ID**, **Feedback**, **AI sentiment**, and **AI category**.

There are three recorded entries of customer feedback:

1.  **October 12, 2024 (ID: 82736481):** A highly positive review for a custom-made pendant, noted for its beauty and craftsmanship. The AI classifies the sentiment as **Positive** and the category as **Compliment**.
2.  **December 19, 2024 (ID: 77654822):** A request to exchange a pair of pearl earrings for a smaller size. The AI classifies the sentiment as **Neutral** and the category as an **Exchange request**.
3.  **December 24, 2024 (ID: 84435116):** A complaint regarding a silver chain that tarnished quickly, leading to a request for a full refund. The AI classifies the sentiment as **Negative** and the category as a **Return request**.

The bottom of the table includes four placeholder rows with generic labels ("yyyy/mm/dd", "##", "Feedback") for future entries.
Enter fullscreen mode Exit fullscreen mode

3. Applying to Other Workspace Services

This approach—using the export URL—is applicable to Google Sheets, Google Docs, and Google Slides. The URL patterns are as follows:

For Google Sheets:

const uri = `https://docs.google.com/spreadsheets/d/${spreadsheetId}/export?format=pdf`;

// Or, for a specific sheet (gid)
const uri = `https://docs.google.com/spreadsheets/d/${spreadsheetId}/export?format=pdf&gid=${sheetId}`;
Enter fullscreen mode Exit fullscreen mode

For Google Docs:

const uri = `https://docs.google.com/document/d/${documentId}/export?format=pdf`;

// Or, for a specific tab
const uri = `https://docs.google.com/document/d/${documentId}/export?format=pdf&tab=${tabId}`;
Enter fullscreen mode Exit fullscreen mode

For Google Slides:

const uri = `https://docs.google.com/presentation/d/${presentationId}/export?format=pdf`;
Enter fullscreen mode Exit fullscreen mode

4. Handling Private Content

In a production environment, you likely do not want to make your files public. If you attempt to use the URL of a private file directly, the API will return the following error:

{"error":{"code":400,"message":"Cannot fetch content from the provided URL.","status":"INVALID_ARGUMENT"}}
Enter fullscreen mode Exit fullscreen mode

To resolve this, you can append an OAuth 2.0 access token to the URL query parameters. (The access token from the service account can also be used.) This allows the Gemini API to fetch the content with the necessary permissions.

For Google Sheets:

The access token must have the scope https://www.googleapis.com/auth/spreadsheets or https://www.googleapis.com/auth/spreadsheets.readonly.

const uri = `https://docs.google.com/spreadsheets/d/${spreadsheetId}/export?format=pdf&access_token=${accessToken}`;
Enter fullscreen mode Exit fullscreen mode

For Google Docs:

The access token must have the scope https://www.googleapis.com/auth/documents or https://www.googleapis.com/auth/documents.readonly.

const uri = `https://docs.google.com/document/d/${documentId}/export?format=pdf&access_token=${accessToken}`;
Enter fullscreen mode Exit fullscreen mode

For Google Slides:

The access token must have the scope https://www.googleapis.com/auth/presentations or https://www.googleapis.com/auth/presentations.readonly.

const uri = `https://docs.google.com/presentation/d/${presentationId}/export?format=pdf&access_token=${accessToken}`;
Enter fullscreen mode Exit fullscreen mode

Utility Script: Retrieving an Access Token

The following helper script uses the gcloud CLI to retrieve a valid access token for testing purposes. Ensure gcloud is installed and authenticated (gcloud auth application-default login) before running this.

import { execSync } from "child_process";

function getAccessToken() {
  // 1. Check if gcloud CLI is installed
  try {
    execSync("gcloud --version", { stdio: "ignore" });
  } catch (error) {
    console.error(
      "\n[Error] Google Cloud SDK (gcloud CLI) not found or failed to run."
    );
    console.error("Please install it by following the official instructions:");
    console.error("https://cloud.google.com/sdk/gcloud");
    process.exit(1);
  }

  // 2. Obtain access token
  try {
    return execSync("gcloud auth print-access-token", {
      encoding: "utf8",
    }).trim();
  } catch (error) {
    console.error("\nError obtaining access token:");
    console.error(error.message);
    console.error(
      "Please ensure you are authenticated with gcloud CLI. Run 'gcloud auth application-default login'."
    );
    process.exit(1);
  }
}
Enter fullscreen mode Exit fullscreen mode

Dynamic Content with Google Apps Script

Google Apps Script (GAS) is a powerful tool for automation and dynamic content generation. By deploying a script as a Web App, we can create a dynamic external URL for the Gemini API.

1. Setting up the Web App

In this example, we create a simple Web App that returns a specific text string. This simulates a dynamic data source.

Create a standalone Google Apps Script file in Google Drive and paste the following code:

fig3

function doGet(e) {
  const text = "The current keyword is 'apple'.";
  return ContentService.createTextOutput(text);
}
Enter fullscreen mode Exit fullscreen mode

Next, deploy the script as a Web App:

  1. Open the script editor.
  2. Click Deploy > New deployment.
  3. Select Web App as the type.
  4. Set "Execute as" to Me.
  5. Set "Who has access" to Anyone.
  6. Click Deploy and copy the Web App URL (https://script.google.com/macros/s/###/exec).

Note on Security:
If you wish to restrict access (e.g., set "Who has access" to Only myself), you must append the access token to the Web App URL, similar to the private file examples above:
https://script.google.com/macros/s/###/exec?access_token=${accessToken}.

Note on Updates:
When modifying the GAS code, you must create a new deployment version to reflect the changes in the Web App URL. Reference. Additional details on GAS Web Apps can be found here.

2. Client Script for GAS Web Apps

Set your Web App URL to the uri variable.

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

const uri =  "https://script.google.com/macros/s/###/exec";
const ai = new GoogleGenAI({});

async function main() {
  const response = await ai.models.generateContent({
    model: "gemini-3-flash-preview",
    contents: [
      createPartFromUri(uri, "text/plain"),
      "What is the current key word?",
    ],
  });
  console.log(response.text);
}

main();
Enter fullscreen mode Exit fullscreen mode

3. Testing Dynamic Updates

When the script is run initially, the output is:

The current keyword is **apple**.
Enter fullscreen mode Exit fullscreen mode

To test the dynamic nature of this integration, modify the GAS code:
Change const text = "The current keyword is 'apple'."; to const text = "The current keyword is 'orange'.";.
Deploy a new version of the Web App.

Running the client script again yields:

The current keyword is **orange**.
Enter fullscreen mode Exit fullscreen mode

This test confirms that the Gemini API always fetches data from the external URL in real-time. This capability is incredibly powerful. It allows Gemini to generate content based on live data feeds, latest news, or real-time calculations performed by Google Apps Script.

Additionally, it is worth noting that GAS Web Apps typically require clients to follow HTTP redirects. Ref. The success of this test indicates that the Gemini API's external URL fetcher correctly handles HTTP redirects, ensuring seamless integration with services like GAS.

Summary

  • The Gemini API now supports external file URLs (up to 100 MB), eliminating the need to upload files beforehand.
  • Google Workspace files (Sheets, Docs, Slides) can be directly ingested by Gemini using their PDF export URLs.
  • Private Workspace files can be accessed securely by appending a valid OAuth 2.0 access token to the URL parameters.
  • Google Apps Script Web Apps allow for the integration of dynamic, real-time data sources into Gemini's generation process.
  • The Gemini API correctly handles HTTP redirects, which is essential for working with Google Apps Script Web Apps and similar services.

Top comments (0)