Hire 
Max Reynolds
Submit
Note: Voiceflow is not responsible for the exchange of services between you and the partner.
Thank you! An email will be sent connecting you with the expert.
Oops! Something went wrong while submitting the form.

Pull from Google Sheets

Template
Function
145
Template
Function
by
Max Reynolds

GET Request to pull data from Google Sheets API.

Created:

Heading

Voiceflow APIs used:

Channels
No items found.
Created By
Max Reynolds
This is some text inside of a div block.

Function Code Snippet

 
export default async function main(args) {
  const { google_sheets_api_key, spreadsheet_link, range } = args.inputVars;

  if (!google_sheets_api_key || !spreadsheet_link || !range) {
    return {
      next: { path: 'error' },
      trace: [{ type: "debug", payload: { message: "Missing required input variables for Google Sheets API function" } }]
    };
  }

  const spreadsheetIdRegex = /\/d\/([a-zA-Z0-9-_]+)/;
  const match = spreadsheetIdRegex.exec(spreadsheet_link);
  if (!match) {
    return {
      next: { path: 'error' },
      trace: [{ type: "debug", payload: { message: "Invalid Google Sheets URL" } }]
    };
  }
  const spreadsheet_id = match[1];

  const url = `https://sheets.googleapis.com/v4/spreadsheets/${spreadsheet_id}/values/${range}?key=${google_sheets_api_key}`;

  try {
    const response = await fetch(url, { method: 'GET', headers: { 'Content-Type': 'application/json' } });
    const responseBody = response.json;

    if (!responseBody || typeof responseBody !== 'object') {
      return {
        next: { path: 'error' },
        trace: [{ type: "debug", payload: { message: "Invalid or missing response body from Google Sheets API" } }]
      };
    }

    // Simplifying the return object for testing
    return {
      outputVars: { sheetData: JSON.stringify(responseBody) }, // Temporarily return the response as a string
      next: { path: 'success' },
      trace: [{ type: "debug", payload: { message: "Response Body: " + JSON.stringify(responseBody) } }]
    };
  } catch (error) {
    return {
      next: { path: 'error' },
      trace: [{ type: "debug", payload: { message: "Error fetching data from Google Sheets: " + error.message } }]
    };
  }
}
copy-icon

Explore More Templates

Build and submit a Template to have it featured in the community.

ghraphic
No items found.
No items found.