How to Verify API Keys for Gemini AI and OpenAI with Google Apps Script
Learn how to verify API keys for Google Gemini AI and OpenAI using Google Apps Script.
Are you developing Google Sheets functions or Google Workspace add-ons that tap into the power of Google Gemini AI or OpenAI? This tutorial explains how you can use Google Apps Script to verify that the API keys provided by the user are valid and working.
The scripts make an HTTP request to the AI service and check if the response contains a list of available models or engines. There’s no cost associated with this verification process as the API keys are only used to fetch the list of available models and not to perform any actual AI tasks.
Verify Google Gemini API Key
The snippet makes a GET request to the Google Gemini API to fetch the list of available models. If the API key is valid, the response will contain a list of models. If the API key is invalid, the response will contain an error message.
const verifyGeminiApiKey = (apiKey) => {
const API_VERSION = 'v1';
const apiUrl = `https://generativelanguage.googleapis.com/${API_VERSION}/models?key=${apiKey}`;
const response = UrlFetchApp.fetch(apiUrl, {
method: 'GET',
headers: { 'Content-Type': 'application/json' },
muteHttpExceptions: true,
});
const { error } = JSON.parse(response.getContentText());
if (error) {
throw new Error(error.message);
}
return true;
};
This snippet works with Gemini API v1. If you are using Gemini 1.5, you need to update the
API_VERSION
variable in the script.
Verify OpenAI API Key
The Apps Script snippet makes a GET request to the OpenAI API to fetch the list of available engines. Unlike Gemini API where the key is passed as a query parameter in the URL, OpenAI requires the API key to be passed in the Authorization
header.
If the API key is valid, the response will contain a list of engines. If the API key is invalid, the response will contain an error message.
const verifyOpenaiApiKey = (apiKey) => {
const apiUrl = `https://api.openai.com/v1/engines`;
const response = UrlFetchApp.fetch(apiUrl, {
method: 'GET',
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${apiKey}` },
muteHttpExceptions: true,
});
const { error } = JSON.parse(response.getContentText());
if (error) {
throw new Error(error.message);
}
return true;
};
Amit Agarwal
Google Developer Expert, Google Cloud Champion
Amit Agarwal is a Google Developer Expert in Google Workspace and Google Apps Script. He holds an engineering degree in Computer Science (I.I.T.) and is the first professional blogger in India.
Amit has developed several popular Google add-ons including Mail Merge for Gmail and Document Studio. Read more on Lifehacker and YourStory