Sarmad DigitalSarmad Digital

Verify API Keys for Gemini AI and OpenAI with Google

Verify API Keys for Gemini AI and OpenAI with Google

Sarmad GardeziSarmad Gardezi
Verify Instagram Account

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.

2const verifyGeminiApiKey = (apiKey) => {
3 const API_VERSION = 'v1';
4 const apiUrl = `${API_VERSION}/models?key=${apiKey}`;
5 const response = UrlFetchApp.fetch(apiUrl, {
6 method: 'GET',
7 headers: { 'Content-Type': 'application/json' },
8 muteHttpExceptions: true,
9 });
10 const { error } = JSON.parse(response.getContentText());
11 if (error) {
12 throw new Error(error.message);
13 }
14 return true;
Who's This For
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.

2const verifyOpenaiApiKey = (apiKey) => {
3 const apiUrl = ``;
4 const response = UrlFetchApp.fetch(apiUrl, {
5 method: 'GET',
6 headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${apiKey}` },
7 muteHttpExceptions: true,
8 });
9 const { error } = JSON.parse(response.getContentText());
10 if (error) {
11 throw new Error(error.message);
12 }
13 return true;

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


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
Sarmad Digital

I help people expand their business through Digital Marketing and Full-Stack Development.


© Copyright 2024. All rights reserved.