【问题标题】:Passing API Key to importJSON Function Script for Google Sheets将 API 密钥传递给 Google 表格的 importJSON 函数脚本
【发布时间】: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


【解决方案1】:

首先,请注意the documentation explicitly states ImportJSONAdvanced() 不能从电子表格中调用(即作为单元格内公式):

 * An advanced version of ImportJSON designed to be easily extended by a script. This version cannot be called from within a 
 * spreadsheet.

此外,您在最佳猜测中提供的参数与the argument documentation for ImportJSONAdvanced() 不一致。供参考:

 * @param {url}           the URL to a public JSON feed
 * @param {fetchOptions}  an object whose properties are options used to retrieve the JSON feed from the URL
 * @param {query}         the query passed to the include function
 * @param {parseOptions}  a comma-separated list of options that may alter processing of the data
 * @param {includeFunc}   a function with the signature func(query, path, options) that returns true if the data element at the given path
 *                        should be included or false otherwise. 
 * @param {transformFunc} a function with the signature func(data, row, column, options) where data is a 2-dimensional array of the data 
 *                        and row & column are the current row and column being processed. Any return value is ignored. Note that row 0 
 *                        contains the headers for the data, so test for row==0 to process headers only.

有趣的是fetchOptions 参数,它作为params 参数传递给UrlFetchAPP.fetch(url, params)。根据the documentationparams是一个可以包含headers参数的对象,可以用来设置HTTP请求的headers。

因此,一种方法是定义您自己的 Apps 脚本函数,该函数包装 ImportJSONAdvanced() 并准备所需的标头。

function ImportJSON_WordsAPI(path, query, parseOptions) {
  var url = 'https://wordsapiv1.p.mashape.com/words' + path;
  var fetchOptions = {
       'headers': {
           'X-Mashape-Key': '<MYKEYHERE>',
           'Accept': 'application/json',
       },
  }
  return ImportJSONAdvanced(url, fetchOptions, query, parseOptions, includeXPath_, defaultTransform_);
}

然后,在这样的单元格中使用该函数:

=ImportJSON_WordsAPI('/words/soliloquy', '/results', 'noInherit,noTruncate')

警告:由于我无权访问 WordsAPI,因此这些都没有经过测试。

【讨论】:

  • 谢谢@chuckx。学过的知识。 下次请仔细阅读文档。根据您的回答和一些外部帮助,我在原始代码的第 255 行添加了一个包装器。有关详细信息,请参阅对我的原始帖子的编辑。它有效。
猜你喜欢
  • 1970-01-01
  • 2012-01-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-25
  • 1970-01-01
相关资源
最近更新 更多