Gemini API in Google Sheets using Apps Script
In Excel we used VBA to call Gemini. If your data is in Google Sheets, then it is even more easy. Google Sheets comes with Apps Script, which can call any web API directly. Nothing to install.
At the end of this page you will have your own formula in Google Sheets, like this:
=GEMINI("Translate to Hindi: " & A2)
Type it in any cell & the answer from Gemini comes in that cell. I have also given a menu option to fill responses for hundreds of rows at once, which is better for bulk work.
Also Read: How to use Gemini API in Excel VBA Macro
Before You Start - Get the API Key
You need a free Gemini API key from Google AI Studio. If you don't have it yet, follow the steps in this article: How to Get Free Gemini API Key.
We are not going to type the key inside the code. Apps Script has a place called Script Properties, where we can store it separately. So, even if you share the sheet or copy the code, the key is not visible in the code.
Steps to Add Gemini Function in Google Sheets
- Open your Google Sheet.
- Go to Extensions -> Apps Script. A new tab opens with the script editor.
- Delete the empty myFunction() code that is already there.
- Copy paste the below code & click the Save icon.
- Click on the gear icon (Project Settings) on the left side.
- Scroll down to Script Properties -> click "Add script property".
- Enter Property as GEMINI_API_KEY & paste your API key in Value. Click "Save script properties".
If you are new to Apps Script, this Hello World program in Google Spreadsheet scripts will help you to understand the editor.
// Gemini model to use. Change this when Google releases a newer model.
const GEMINI_MODEL = 'gemini-3.8-flash';
// Send a prompt to Gemini API & return the answer as text
function askGemini(prompt) {
const apiKey = PropertiesService.getScriptProperties().getProperty('GEMINI_API_KEY');
if (!apiKey) {
return 'Error: Add GEMINI_API_KEY in Project Settings -> Script Properties';
}
const url = 'https://generativelanguage.googleapis.com/v1beta/models/' + GEMINI_MODEL + ':generateContent';
const payload = {
contents: [ { parts: [ { text: prompt } ] } ]
};
const options = {
method: 'post',
contentType: 'application/json',
headers: { 'x-goog-api-key': apiKey },
payload: JSON.stringify(payload),
muteHttpExceptions: true // To read the error message instead of script failing
};
const response = UrlFetchApp.fetch(url, options);
const data = JSON.parse(response.getContentText());
// Check Return Code from API Server & Proceed
if (response.getResponseCode() !== 200) {
return 'Error ' + response.getResponseCode() + ': ' + (data.error ? data.error.message : '');
}
if (!data.candidates || !data.candidates[0].content) {
return 'No response from Gemini';
}
// Join all text parts of the answer
return data.candidates[0].content.parts.map(function (p) { return p.text || ''; }).join('');
}
/**
* Sends a prompt to Google Gemini & returns the answer.
*
* @param {string} prompt The question or instruction to Gemini.
* @return The answer from Gemini.
* @customfunction
*/
function GEMINI(prompt) {
if (prompt === '' || prompt === null) {
return '';
}
prompt = String(prompt);
// Use cached answer if the same prompt was asked in last 6 hours
const cache = CacheService.getScriptCache();
const cacheKey = Utilities.base64Encode(
Utilities.computeDigest(Utilities.DigestAlgorithm.MD5, prompt)
);
const cached = cache.get(cacheKey);
if (cached) {
return cached;
}
const answer = askGemini(prompt);
if (answer.indexOf('Error') !== 0 && answer.length < 90000) {
cache.put(cacheKey, answer, 21600);
}
return answer;
}
Now go back to the sheet & type this in any cell:
=GEMINI("What is the capital of Canada?")
It will show "Loading..." for few seconds & then the answer. You can also refer to cells, for example =GEMINI("Write a one line product description for: " & A2) & drag it down.
What does this code do?
- askGemini: Builds the request in the JSON format Gemini expects, sends it with UrlFetchApp.fetch & picks the answer text from candidates -> content -> parts.
- GEMINI: This is the custom formula. The @customfunction comment makes it appear in the formula suggestions, just like SUM or VLOOKUP.
- CacheService: Google Sheets recalculates formulas when the sheet is opened or changed. Without cache, every recalculation will call the API again & waste your free quota. With this, the same prompt is answered from cache for 6 hours.
Fill Gemini Responses for All Rows - Using Menu
The formula is good for few cells. But if you have 500 rows, 500 formulas will fire together & you will hit the rate limit immediately. Also, formulas can recalculate & give a slightly different answer next time.
For bulk work, it is better to write the answer as a fixed value. Add this code below the previous code in the same script file & save.
// Adds a "Gemini" menu when the sheet is opened
function onOpen() {
SpreadsheetApp.getUi()
.createMenu('Gemini')
.addItem('Fill responses in Column B', 'fillGeminiResponses')
.addToUi();
}
// Reads prompt from Column A & writes Gemini answer in Column B
function fillGeminiResponses() {
const sheet = SpreadsheetApp.getActiveSheet();
const lastRow = sheet.getLastRow();
for (let i = 2; i <= lastRow; i++) {
const prompt = sheet.getRange(i, 1).getValue();
const answer = sheet.getRange(i, 2).getValue();
// Process only rows that have a prompt & no answer yet
if (prompt !== '' && answer === '') {
sheet.getRange(i, 2).setValue(askGemini(String(prompt)));
SpreadsheetApp.flush(); // Show the answer in sheet immediately
Utilities.sleep(2000); // Small wait to stay within rate limit
}
}
SpreadsheetApp.getUi().alert('All rows processed');
}
Reload the Google Sheet. You will see a new menu "Gemini" next to Help. Put your prompts in Column A from row 2 & click Gemini -> Fill responses in Column B.
First time, Google will ask for permission because the script connects to an external service. Click Continue, choose your account. If it shows "Google hasn't verified this app", click Advanced -> Go to (your project name). This warning comes because it is your own script & not a published app.
Things to Know
- 30 second limit for formulas: A custom function must finish within 30 seconds. For long answers it may show an error. Ask for shorter answers or use the menu option.
- 6 minute limit for scripts: The menu macro stops after about 6 minutes in a free Gmail account. Just run it again. It skips rows that already have an answer & continues from where it stopped.
- Response has ** and # symbols: Gemini replies in Markdown by default. Add "Reply in plain text" to your prompt.
- Error 429: Too many requests. Increase the Utilities.sleep value. Check the free tier rate limits to know more.
- Sharing the sheet: Script Properties are not visible to viewers, but editors of the sheet can open the script & see it. Share edit access only with people you trust.
Try it with something you do every week. For example, a column of messy customer names & addresses, and a prompt to clean & format them. Once the answers are in Column B, you can use the normal Sheets tricks like removing duplicates on the cleaned data.