Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use an external API in Google Apps Script that requires an API Key? [duplicate]

Is it possible to use external API's within google apps script that require API key's?

How would you get data from an API that requires a key using Google Apps Script?

like image 386
CTOverton Avatar asked Oct 17 '25 07:10

CTOverton


1 Answers

Apps Script has UrlFetchApp which fetches resources and communicate with other hosts over the Internet. This includes URL requests with API keys.

Example from this Using Google Sheets and Google Apps Script to Work with APIs:

sample code:

function myFunction() {
  var ss = SpreadsheetApp.getActiveSpreadsheet(); //get active spreadsheet
  var sheet = ss.getSheetByName('data'); //get sheet by name from active spreadsheet


  var apiKey = 'Your API Key'; //apiKey for forecast.io weather api
  var long = "-78.395602"; 
  var lat =  "37.3013648";    
  var url = 'https://api.forecast.io/forecast/' + apiKey +"/" + lat +"," + long; //api endpoint as a string 

  var response = UrlFetchApp.fetch(url); // get api endpoint
  var json = response.getContentText(); // get the response content as text
  var data = JSON.parse(json); //parse text into json

  Logger.log(data); //log data to logger to check

  var stats=[]; //create empty array to hold data points

  var date = new Date(); //create new date for timestamp

  //The following lines push the parsed json into empty stats array
    stats.push(date);//timestamp 
    stats.push(data.currently.temperature); //temp
    stats.push(data.currently.dewPoint); //dewPoint
    stats.push(data.currently.visibility); //visibility

  //append the stats array to the active sheet 
  sheet.appendRow(stats)

}
like image 121
ReyAnthonyRenacia Avatar answered Oct 19 '25 22:10

ReyAnthonyRenacia



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!