How to Use Google Apps Script to Call the Gemini API and Create a Google Doc with AI-Generated Content

📢 Introduction

Imagine being able to generate AI-powered content and automatically store it in a Google Doc. With Google Apps Script and the Gemini API, you can achieve this in just a few lines of code.

This guide will walk you through a simple script that:

  1. Calls the Gemini API to generate AI-powered responses.
  2. Creates a new Google Doc.
  3. Populates the document with both the prompt and the AI-generated response.

By the end, you’ll have a fully functional script that allows you to generate and save AI content with one click. This script is perfect for creating research papers, content ideas, marketing materials, and more.


🎉 What Will This Script Do?

This script will:

  1. Call the Gemini API to get an AI-generated response for a given prompt.
  2. Create a new Google Doc called Gemini API Response.
  3. Insert the prompt and AI response into the document.
  4. Log the URL of the document so you can access it quickly.

📘 Full Apps Script Code

Here is the complete script to call the Gemini API, create a new Google Doc, and populate it with AI-generated content.

const geminiApiKey = 'YOUR_GEMINI_API_KEY_HERE'; // Replace with your actual Gemini API Key
const geminiModel = `https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash-latest:generateContent?key=${geminiApiKey}`;

function callGemini(q, temperature=0) {
const payload = { contents: [{ parts: [{ text: q }] }] };
const options = {
'method': 'post',
'contentType': 'application/json',
'payload': JSON.stringify(payload)
};
const response = UrlFetchApp.fetch(geminiModel, options);
const data = JSON.parse(response.getContentText());
const content = data["candidates"][0]["content"]["parts"][0]["text"];
return content;
}

function createDocWithGeminiResponse() {
const prompt = "What is the future of AI"; // The prompt for the Gemini API
const geminiResponse = callGemini(prompt); // Get the response from Gemini API

// Step 1: Create a new Google Doc
const doc = DocumentApp.create('Gemini API Response');
const docId = doc.getId();
const body = doc.getBody();

// Step 2: Populate the document with the prompt and the AI response
body.appendParagraph('**Prompt**:').setHeading(DocumentApp.ParagraphHeading.HEADING2);
body.appendParagraph(prompt); // Add the prompt

body.appendParagraph('**Gemini Response**:').setHeading(DocumentApp.ParagraphHeading.HEADING2);
body.appendParagraph(geminiResponse); // Add the response from the Gemini API

// Log the URL of the new Google Doc
const docUrl = doc.getUrl();
Logger.log(`New document created: ${docUrl}`);
}

📘 How It Works

  1. Call Gemini AP const response = UrlFetchApp.fetch(geminiModel, options); const data = JSON.parse(response.getContentText()); The script sends a POST request to the Gemini API using UrlFetchApp. The payload contains the text prompt for the AI model, and the response is parsed as JSON. The script extracts the AI-generated content from the data["candidates"] object.
  2. Create Google Doc const doc = DocumentApp.create('Gemini API Response'); A new Google Doc called Gemini API Response is created, and the document ID is stored in the variable docId.
  3. Insert Prompt and AI Response body.appendParagraph('**Prompt**:').setHeading(DocumentApp.ParagraphHeading.HEADING2); body.appendParagraph(prompt); body.appendParagraph('**Gemini Response**:').setHeading(DocumentApp.ParagraphHeading.HEADING2); body.appendParagraph(geminiResponse); The script formats the document to display the Prompt and the AI Response as headings and text, providing a clean, professional format.
  4. Log Document URL const docUrl = doc.getUrl(); Logger.log(`New document created: ${docUrl}`); The script logs the URL of the new document, which can be accessed from the View > Logs menu in the Apps Script editor.

📘 Usage Instructions

  1. Add the Script
    • Open Google Sheets or Google Docs.
    • Click ExtensionsApps Script.
    • Paste the script above into the editor.
  2. Update the API Key
    • Replace YOUR_GEMINI_API_KEY_HERE with your Gemini API Key.
  3. Run the Script
    • Click Run (▶️) next to createDocWithGeminiResponse().
    • Authorize the script to access Google Docs and external services.
  4. View the Results
    • View the Logs (View → Logs) to get the URL of the new document.
    • Open the document to see the AI-generated response.

📘 Example Output

Prompt

What is the future of AI?

Gemini Response

The future of AI holds immense potential, with advancements expected in automation, natural language processing, and machine learning. As AI systems become more sophisticated, they will enhance industries such as healthcare, education, and customer service. However, ethical considerations and the potential displacement of human jobs remain key issues. The next decade may see AI playing a greater role in decision-making, autonomous vehicles, and creative processes like art and design.

📘 Customization Options

1️⃣ Change the Prompt

Change the prompt to something else, like:

const prompt = "Explain the role of blockchain in modern finance";

2️⃣ Customize the Document Name

Change the name of the document from Gemini API Response to something like:

const doc = DocumentApp.create('AI Content Report');

3️⃣ Generate Multiple Prompts

If you want to generate responses for multiple prompts in one document, modify the script like this:

const prompts = [
"What is the future of AI?",
"How does blockchain technology work?",
"What are the benefits of clean energy?"
];

prompts.forEach((prompt, index) => {
const geminiResponse = callGemini(prompt);
body.appendParagraph(`📘 **Prompt ${index + 1}**: ${prompt}`).setHeading(DocumentApp.ParagraphHeading.HEADING2);
body.appendParagraph(`💡 **Response**: ${geminiResponse}`);
});

📘 Possible Use Cases

Use CaseDescription
Research ReportsGenerate content for research and analysis automatically.
Content GenerationGet AI-powered content ideas for blogs, ads, and marketing.
Educational ToolsUse AI to generate learning content or course materials.
Creative WritingGenerate creative ideas, short stories, or character concepts.
Product DescriptionsAutomatically generate descriptions for products.

📘 Key Features Recap

  • Call Gemini API: Send a prompt to the AI model and receive a response.
  • Create Google Doc: Automatically generate a new Google Doc.
  • Format the Content: Display the prompt and AI response in a professional layout.

📘 Final Thoughts

This Google Apps Script allows you to generate AI content from the Gemini API and store it in Google Docs. The possibilities for this automation are endless, from content generation to research automation and even AI-powered document creation.

This script is fully customizable. You can change the API prompt, format the document, or call the API multiple times to get a list of responses.

If you’d like to see more customizations, explanations, or different API integrations, let me know! 😊