How to Verify API Keys for Gemini AI and OpenAI with Google Apps Script

Learn how to validate 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 user-supplied API keys 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 is no cost associated with this verification process because the API keys are only used to fetch the list of available models and not to perform any actual AI operations.

Verify Google Gemini API Key

The snippet makes a GET request to the Google Gemini API to fetch a 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 API_VERSION variable in the script.

Verify the OpenAI API key

The Apps Script snippet makes a GET request to the OpenAI API to get a list of available engines. Unlike the Gemini API where the key is passed as a query parameter in the URL, the OpenAI API key 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;
};

Leave a Comment