【发布时间】:2020-08-06 19:18:54
【问题描述】:
我正在尝试使用 importJSON(来自 Github 的 Google 表格中的自定义 Google 脚本函数)从 WordsAPI 导入数据。从不需要身份验证的 API 导入信息很容易。但是,WordsAPI 需要一个密钥,我不知道如何将密钥传递给函数。我最好的猜测是:
=ImportJSONAdvanced("https://wordsapiv1.p.mashape.com/words/example/examples", "wordsapiv1.p.rapidapi.com", "<MYKEYHERE>", "/examples/", "noInherit,noTruncate,Headers")
但是,这会导致错误:Bad value (line 220).
代码的相关部分如下。前往 Github 的 ImportJSON.gs 获取完整代码。
function ImportJSONAdvanced(url, fetchOptions, query, parseOptions, includeFunc, transformFunc) {
var jsondata = UrlFetchApp.fetch(url, fetchOptions);
var object = JSON.parse(jsondata.getContentText());
return parseJSONObject_(object, query, parseOptions, includeFunc, transformFunc);
}
我已经阅读了documentation regarding authentication at the WordsAPI site,他们建议使用以下代码 sn-p:
// These code snippets use an open-source library. http://unirest.io/nodejs
unirest.get("https://wordsapiv1.p.mashape.com/words/soliloquy")
.header("X-Mashape-Key", "<MYKEYHERE>")
.header("Accept", "application/json")
.end(function (result) {
console.log(result.status, result.headers, result.body);
});
我也通读了Google Apps Script documentation on Authorization for Google Services,但这对我来说意义不大。问题是否可能是 ImportJSONAdvanced 使用 POST 而 WordsAPI 想要 GET?如果是这种情况,我该如何修改代码以使其正常工作?
感谢您的阅读。任何帮助将不胜感激。
编辑:基于@chuckx cmets 和其他帮助。我在original code 的第 255 行添加了以下内容。
/**
*
* Wrapper for WordsAPI
*
* @param {url} the URL to a http basic auth protected JSON feed
* @param {api_key} the api_key for authentication
* @param {query} always = ""
* @param {parseOptions} a comma-separated list of options that may alter processing of the data (optional)
*/
function ImportJSON_words(url, api_key, query, parseOptions) {
var header = {
headers: {
'X-Mashape-Key': api_key,
'Accept': 'application/json'
}
}
return ImportJSONAdvanced(url, header, query, parseOptions, includeXPath_, defaultTransform_)
}
有效。
【问题讨论】:
-
我正在尝试使用另一个 API 服务 Blockfrost.io 来完成相同的操作,以将 Cardano 区块链数据导入谷歌表格。那么如何调用单元格内的函数呢?另外,您在哪里定义变量
api_key?谢谢
标签: google-apps-script google-sheets api-key