Find out how to Confirm API Keys for Gemini AI and OpenAI with Google Apps Script

Shubham
3 Min Read

Discover ways to confirm API keys for Google Gemini AI and OpenAI utilizing Google Apps Script.

Are you growing Google Sheets capabilities or Google Workspace add-ons that faucet into the ability of Google Gemini AI or OpenAI? This tutorial explains how you should utilize Google Apps Script to confirm that the API keys offered by the consumer are legitimate and dealing.

The scripts make an HTTP request to the AI service and verify if the response accommodates an inventory of accessible fashions or engines. There’s no price related to this verification course of because the API keys are solely used to fetch the checklist of accessible fashions and to not carry out any precise AI duties.

Confirm Google Gemini API Key

The snippet makes a GET request to the Google Gemini API to fetch the checklist of accessible fashions. If the API secret’s legitimate, the response will comprise an inventory of fashions. If the API secret’s invalid, the response will comprise an error message.

const verifyGeminiApiKey = (apiKey) => {
  const API_VERSION = 'v1';
  const apiUrl = `https://generativelanguage.googleapis.com/${API_VERSION}/fashions?key=${apiKey}`;
  const response = UrlFetchApp.fetch(apiUrl, {
    methodology: 'GET',
    headers: { 'Content material-Kind': 'utility/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. In case you are utilizing Gemini 1.5, you could replace the API_VERSION variable within the script.

Confirm OpenAI API Key

The Apps Script snippet makes a GET request to the OpenAI API to fetch the checklist of accessible engines. Not like Gemini API the place the secret is handed as a question parameter within the URL, OpenAI requires the API key to be handed within the Authorization header.

If the API secret’s legitimate, the response will comprise an inventory of engines. If the API secret’s invalid, the response will comprise an error message.

const verifyOpenaiApiKey = (apiKey) => {
  const apiUrl = `https://api.openai.com/v1/engines`;
  const response = UrlFetchApp.fetch(apiUrl, {
    methodology: 'GET',
    headers: { 'Content material-Kind': 'utility/json', Authorization: `Bearer ${apiKey}` },
    muteHttpExceptions: true,
  });
  const { error } = JSON.parse(response.getContentText());
  if (error) {
    throw new Error(error.message);
  }
  return true;
};
Share This Article
Leave a comment

Leave a Reply

Your email address will not be published. Required fields are marked *