如何从 google 脚本向 BigQuery 发出正确的 HTTP 请求

how to make a correct HTTP request to BigQuery from google script

我正在使用 google 脚本 API 尝试从 BiqQuery 获取 table 的模式...不知道为什么这么麻烦。

我正在发送这样的请求:

let url =  'https://bigquery.googleapis.com/bigquery/v2/projects/'+ projectId +'/datasets/'+ datasetId +'/tables/' +tableId; 

 var response = UrlFetchApp.fetch(url)

我收到这样的回复:

Exception: Request failed for https://bigquery.googleapis.com returned code 401. Truncated server response: { "error": { "code": 401, "message": "Request is missing required authentication credential. Expected OAuth 2 access token, login cookie ... (use muteHttpExceptions option to examine full response) (line 68, file "bigQuery")

我已经能够将数据加载到 bigQuery 好...不知道为什么这不起作用。我查看了清单中的 OAuth 字段,脚本确实可以访问 bigQuery...

将此添加到 UrlFetch 请求的选项字段时也没有成功

var authHeader = 'Basic ' + Utilities.base64Encode(USERNAME + ':' + PASSWORD);
    var options = {
      headers: {Authorization: authHeader}
    }

使用不记名令牌

BigQuery API 拒绝您的请求的原因是端点需要以下范围之一与访问令牌一起提供才能工作,但请求中缺少它:

https://www.googleapis.com/auth/bigquery
https://www.googleapis.com/auth/cloud-platform
https://www.googleapis.com/auth/bigquery.readonly
https://www.googleapis.com/auth/cloud-platform.read-only

这里的实际问题是基本授权方案缺少有关任何声明的信息,仅发送正确的凭据。由于您直接使用 UrlFetch 服务请求端点,尽管在清单中正确指定了范围,但它们不会被发送过来。

ScriptApp service now provides an easy method to get a valid bearer token without using an OAuth 2.0 library or building the flow from scratch: getOAuthToken。将它作为不记名令牌传递给 Authorization header,你应该准备就绪:

const token = ScriptApp.getOAuthToken();

const options = {
  headers : {
    Authorization : `Bearer ${token}`
  }
};


使用高级服务

作为替代方案,有一个官方 advanced service 作为 BigQuery REST API 的包装器,它将为您管理身份验证和响应解析。

You must enable the BigQuery advanced service before using it

另请注意,高级服务标识符是可配置的,因此您必须引用您选择的标识符。

在您的情况下,可以按如下方式使用该服务(假设您使用默认的 BigQuery 标识符)。还有类型为 object 的第四个参数,其中包含可选参数(此处未显示):

Bigquery.Tables.get("projectId","datasetId", "tableId");

上面的方法链对应BigQuery的tables.get方法API.