Guide to Verify API keys for Gemini AI and OpenAI using Google Apps Script

Verify API Key Gemini AI: Send a GET request to the Gemini API endpoint to retrieve the list of available models. If the API key is valid, the response will include a list of models; otherwise, an error message will be returned.

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

    Note : “This snippet is designed to work with Gemini API v1. If you are using Gemini 1.5, please ensure to update the API_VERSION variable in the script accordingly.”

    Verify the OpenAI API Key: initiate a GET request to the OpenAI API endpoint for retrieving the list of available engines. Unlike the Gemini API, OpenAI mandates the inclusion of the API key in the Authorization header. Upon validation of the API key, the response will feature a comprehensive list of engines; otherwise, an error message will be returned.

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

    These snippets should be included in your Google Apps Script project. You can call these functions by passing the API key as an argument to check if they are valid, and the functions will handle any exceptions that may occur during the verification process.

    Scroll to Top