google-apps-script - 将 API key 传递给 Google 表格的 importJSON 函数脚本

标签 google-apps-script google-sheets api-key

我正在尝试从 WordsAPI 导入数据使用 importJSON ,来自 Github 的 Google 表格中的自定义 Google 脚本函数。从不需要身份验证的 API 导入信息很容易。但是,WordsAPI 需要一个 key ,我不知道如何将 key 传递给函数。我最好的猜测是:

=ImportJSONAdvanced("https://wordsapiv1.p.mashape.com/words/example/examples", "wordsapiv1.p.rapidapi.com", "<MYKEYHERE>", "/examples/", "noInherit,noTruncate,Headers")

但是,这会导致错误:Bad value (line 220).

代码的相关部分如下。转到 ImportJSON.gs在 Github 上获取完整代码。

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他们建议使用以下代码片段:

// 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 评论和其他帮助。我在第 255 行将以下内容添加到 original code .

/**
 *
 * 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_)
}

有效。

最佳答案

首先,请注意 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 documentation , params 是一个对象,可以包含一个headers参数,可以用来设置HTTP请求的headers。

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

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。

关于google-apps-script - 将 API key 传递给 Google 表格的 importJSON 函数脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59710389/

相关文章:

google-apps-script - 使用 Google Apps 脚本在 Gmail 中创建新过滤器

google-apps-script - Google Apps 脚本中表单的动态选择选项

javascript - 如何修复 {"result":"error","error": {"name" :"Exception"}} in google apps scripts

javascript - 是否可以将 js 变量发送到 google 表格? (不是表单数据)

key - 使用 gcloud 创建 API key ?

ios - 在 Swift 上的哪里存储 API key ?

javascript - 提供 API key 时,Google map 将无法工作/此页面无法显示 Google map 元素

javascript - 在 Google apps 脚本中获取 json 数组中的键->值

javascript - 需要帮助循环 3 个循环以在 Google 脚本中附加数据

r - 在 `googleAuthR` 中使用来自 `googlesheets` 的 token