Sarmad DigitalSarmad Digital
Coding

Verify API Keys for Gemini AI and OpenAI with Google

Verify API Keys for Gemini AI and OpenAI with Google

Sarmad Gardezi AvatarSarmad Gardezi
Verify API Keys for Gemini AI and OpenAI with Google

Verify API Keys for Gemini AI and OpenAI with Google

Verify API Keys for Gemini AI and OpenAI with Google

Looking to leverage the power of Google Gemini AI or OpenAI in your Google Sheets functions or Google Workspace add-ons? This blog post dives into a simple yet effective technique using Google Apps Script to validate your users' API keys.

Our script utilizes HTTP requests to interact with the AI service and confirm the presence of a list containing available models or engines within the response. This verification comes completely free of charge, as the API keys are solely used to retrieve this model list and not for actual AI tasks.


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.

Validate OpenAI API Key

This Apps Script snippet conducts a GET request to the OpenAI API in order to retrieve the roster of accessible engines. Unlike the Gemini API, where the key is included as a query parameter within the URL, OpenAI mandates the API key to be transmitted through the Authorization header.

Should the API key prove legitimate, the ensuing response will furnish a catalog of engines. Conversely, if the API key is deemed invalid, the response will furnish 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;
};

I am looking forward to seeing your open-source projects! Feel free to share them with me on Twitter.

Coding

Let's challenge your product.

Fresh eyes help generate new perspectives. Book a free call in which we identify opportunities and broken flows in your web app.

20min call Get product feedback