How to Make OpenAI API calls from Google Sheets?

I often have a need of making OpenAI API calls directly from Google Sheets to prepare some data.

Earlier, I used to use Add-Ons like GPT for Sheets, but slowly they all became paid.

So I figured a free alternative for my needs. I’m sharing it here so you all can use it as well.

Step 1: Generate OpenAI API Key

Go to this link : https://platform.openai.com/api-keys

generating open ai api key

Click on “Create new secret key”

generating open ai api key

Give it a name so you can identify where the key was used.

save your openai api key

Copy the key as you will need it later.

Step 2: Create an App Script

create an apps script

This will bring you to a view like this.

apps script untitled project

Remove everything from the code section, and Paste this code into the App Script

Apps Script Code

function OPENAI(prompt, systemMessage, temperature, model) {
  const apiKey = 'YOUR_OPENAI_API_KEY'; // Replace this securely
  const url = 'https://api.openai.com/v1/chat/completions';

  // Set defaults if values are not provided
  systemMessage = systemMessage || "You are a helpful assistant.";
  temperature = typeof temperature === 'number' ? temperature : 0.7;
  model = model || "gpt-4o";

  if (!prompt || prompt.trim() === "") {
    return "❌ Please provide a prompt.";
  }

  const payload = {
    model: model,
    messages: [
      { role: "system", content: systemMessage },
      { role: "user", content: prompt }
    ],
    temperature: temperature
  };

  const options = {
    method: 'post',
    contentType: 'application/json',
    headers: {
      Authorization: 'Bearer ' + apiKey
    },
    payload: JSON.stringify(payload),
    muteHttpExceptions: true
  };

  try {
    const response = UrlFetchApp.fetch(url, options);
    const json = JSON.parse(response.getContentText());

    if (!json.choices || !json.choices[0]) {
      return "⚠️ No response from OpenAI.";
    }

    return json.choices[0].message.content.trim();
  } catch (e) {
    return "❌ Error: " + e.message;
  }
}

Replace YOUR_OPENAI_API_KEY with your own API Key that you generated.

Click on Save Button.

openai code into apps script

Step 3: Make an OpenAI call from Google Sheet.

Now go to your Google Sheet, and you can make an API call.

how to use openai call in google sheet cell

It should return a response like this.

how to use openai call in google sheet cell

To make the experience a little bit better, I’ve baked in some customization like model selection, system prompt, temperature and error handling. Here are some examples of how you can use them all.

how to use openai call in google sheet cell different scenarios

🚀 You’re All Set!

With just a few lines of code, you’ve unlocked the power of GPT right inside Google Sheets — totally free.

Leave a Reply

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