How to Automatically Create Multiple Sub-folders in Google Drive.

Find out how to use Google Apps Script to validate API keys for Google Gemini AI and OpenAI.

How to Automatically Create Multiple Sub-folders in Google Drive.

Are you creating Google Sheets functions or Google Workspace extensions that leverage OpenAI or Google Gemini AI? This tutorial shows you how to use Google Apps, Google Drive Script to confirm that the user-provided API keys are legitimate and operational.

The scripts send an HTTP request to the AI service and determine whether a list of available models or engines is included in the response. Since the API keys are just needed to retrieve the list of available models and aren't really used to carry out any AI operations, there is no cost involved in this verification procedure.

Verify Google Gemini API Key

To retrieve the list of available models, the snippet sends a GET request to the Google Gemini API. A list of models will be included in the response if the API key is legitimate. An error notice will appear in the response if the API key is invalid.

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;
};

Verify OpenAI API Key

The list of accessible engines is retrieved by the Apps Script snippet by sending a GET request to the OpenAI API. OpenAI requires the API key to be given in the authorization header, in contrast to the Gemini API, which accepts the key as a query parameter in the URL.

A list of engines will be included in the response if the API key is legitimate. An error notice will appear in the response if the API key is invalid.

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;
};