Verify Gemini AI and OpenAI API Keys in Google Apps Script

Introduction
In the era of generative AI, developers often rely on powerful models such as Google Gemini AI and OpenAI to enhance applications, automate workflows, and generate content. Before any request can be sent, a valid API key must be supplied, and ensuring that the key works correctly is a critical first step. This article walks you through the process of verifying API keys for both Gemini AI and OpenAI directly from Google Apps Script. You will learn why verification matters, how to prepare your script environment, and the exact code snippets needed to test each service. By the end, you’ll have a reliable, reusable routine that confirms your keys are active, correctly scoped, and ready for production use.

Understanding API Keys and Their Role

API keys act as digital passports that grant your script permission to call external AI services. Both Gemini AI and OpenAI expect the key to be sent in the Authorization header, but the format differs slightly:

  • OpenAI: Authorization: Bearer YOUR_OPENAI_KEY
  • Gemini AI: Authorization: Bearer YOUR_GEMINI_KEY

Beyond simple authentication, keys also define usage limits, billing tiers, and access to specific model versions. Verifying a key early prevents hidden runtime errors, protects against unexpected charges, and helps you quickly spot mis‑typed or revoked credentials.

Setting Up Google Apps Script Environment

Google Apps Script (GAS) provides a cloud‑based JavaScript runtime that integrates seamlessly with Google Workspace. Follow these steps to prepare your environment:

  • Open Google Drive, click New → More → Google Apps Script.
  • Rename the project (e.g., “AI Key Verifier”).
  • Enable the UrlFetchApp service – it is available by default, but you must grant permission the first time you run a request.
  • Create two script properties to store your keys securely:
    PropertiesService.getScriptProperties().setProperty('OPENAI_KEY', 'your-openai-key');
    PropertiesService.getScriptProperties().setProperty('GEMINI_KEY', 'your-gemini-key');
    

Storing keys in script properties keeps them out of the source code, reducing accidental exposure when sharing the script.

Implementing Verification for OpenAI API Key

The most straightforward way to test an OpenAI key is to call the models endpoint, which returns a list of models accessible to the key. A successful 200 response confirms validity.

function verifyOpenAIKey() {
  const key = PropertiesService.getScriptProperties().getProperty('OPENAI_KEY');
  const url = 'https://api.openai.com/v1/models';
  const options = {
    method: 'get',
    muteHttpExceptions: true,
    headers: {
      'Authorization': 'Bearer ' + key,
      'Content-Type': 'application/json'
    }
  };
  const response = UrlFetchApp.fetch(url, options);
  const code = response.getResponseCode();
  if (code === 200) {
    Logger.log('✅ OpenAI key is valid.');
    return true;
  } else {
    Logger.log('❌ OpenAI key verification failed (status ' + code + ').');
    return false;
  }
}

This function logs a clear success or failure message. You can extend it to parse the JSON payload and display the model list, giving you immediate feedback that the key not only works but also has access to the expected model versions.

Implementing Verification for Gemini AI API Key

Gemini AI provides a similar endpoint, /v1beta/models, which returns available models when the key is valid. The verification logic mirrors the OpenAI example, with a few nuances:

  • The base URL is https://generativelanguage.googleapis.com.
  • Gemini expects the API key as a query parameter ?key=YOUR_KEY in addition to the Authorization header for some configurations.
function verifyGeminiKey() {
  const key = PropertiesService.getScriptProperties().getProperty('GEMINI_KEY');
  const url = 'https://generativelanguage.googleapis.com/v1beta/models?key=' + key;
  const options = {
    method: 'get',
    muteHttpExceptions: true,
    headers: {
      'Authorization': 'Bearer ' + key,
      'Accept': 'application/json'
    }
  };
  const response = UrlFetchApp.fetch(url, options);
  const code = response.getResponseCode();
  if (code === 200) {
    Logger.log('✅ Gemini AI key is valid.');
    return true;
  } else {
    Logger.log('❌ Gemini AI key verification failed (status ' + code + ').');
    return false;
  }
}

Running this function will confirm whether the Gemini key can retrieve the model catalog. If the response code is anything other than 200, examine the error body – it often contains a message such as “API key not valid” or “billing disabled,” which helps you troubleshoot quickly.

Putting It All Together: A Unified Verification Routine

For convenience, you may want a single entry point that checks both keys and reports a combined status. The following script demonstrates how to orchestrate the two checks and return a concise summary:

function verifyAllKeys() {
  const results = {
    openai: verifyOpenAIKey(),
    gemini: verifyGeminiKey()
  };
  if (results.openai && results.gemini) {
    Logger.log('✅ Both API keys are valid and ready for use.');
  } else {
    Logger.log('⚠️ One or more keys failed verification. Details: ' + JSON.stringify(results));
  }
  return results;
}

This pattern makes it easy to integrate key verification into larger workflows, such as automated deployment pipelines or scheduled health‑check triggers within Google Workspace.

Conclusion
Verifying API keys for Google Gemini AI and OpenAI directly from Google Apps Script is a simple yet essential practice that safeguards your applications against authentication errors and unexpected billing issues. By understanding the role of keys, preparing a secure GAS environment, and implementing targeted verification functions for each provider, you create a robust foundation for any AI‑driven project. The unified routine illustrated above not only streamlines the testing process but also offers a reusable template for future services. Armed with these techniques, you can confidently deploy AI integrations, knowing that your credentials are valid, correctly scoped, and ready to power the next generation of intelligent workflows.

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Digital Malayali