如何在需要 API 密钥的 Google Apps 脚本中使用外部 API? [复制]
Posted
技术标签:
【中文标题】如何在需要 API 密钥的 Google Apps 脚本中使用外部 API? [复制]【英文标题】:How to use an external API in Google Apps Script that requires an API Key? [duplicate] 【发布时间】:2018-10-28 01:25:09 【问题描述】:是否可以在需要 API 密钥的谷歌应用脚本中使用外部 API?
如何使用 Google Apps 脚本从需要密钥的 API 获取数据?
【问题讨论】:
问题太宽泛了。 developers.google.com/apps-script/reference/url-fetch/… 【参考方案1】:Apps 脚本有UrlFetchApp,它获取资源并通过 Internet 与其他主机通信。这包括带有 API 密钥的 URL 请求。
来自这个Using Google Sheets and Google Apps Script to Work with APIs的例子:
示例代码:
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)
【讨论】:
永远不要将 API 密钥作为纯文本存储在您的源代码中。以上是关于如何在需要 API 密钥的 Google Apps 脚本中使用外部 API? [复制]的主要内容,如果未能解决你的问题,请参考以下文章
使用 Google Apps 脚本在 Blogger 中创建帖子
如何使用 Google Apps 脚本执行 API + Java 创建 Google 表单?
运行Chromium浏览器缺少google api密钥无法登录谷歌账号的解决办法
如何在 Google Apps 脚本中使用 UrlFetchApp 发出 Drive API 批处理请求