我正在尝试使用Google Apps脚本使用新的Google文档API。由于新API尚未作为扩展服务提供,我尝试使用UrlFetchApp()但是失败了。
为我天真的尝试道歉:
function apiCall(){
var API_KEY = 'YOUR_API_KEY';
var username = 'YOUR_USERNAME';
var password = 'YOU_PASSWORD';
var DOC_ID = 'YOUR_DOC_ID';
var root = 'https://docs.googleapis.com/v1/documents/';
var endpoint = DOC_ID;
var query = '?key=' + API_KEY;
var params = {
'method': 'GET',
'muteHttpExceptions': true,
'headers': {
'Authorization': 'Basic ' + Utilities.base64Encode(username + ':' + password)
}
};
var response = UrlFetchApp.fetch(root + endpoint + query, params);
var data = response.getContentText();
var json = JSON.parse(data);
Logger.log(json);
}
我收到以下回复:
{error={code=401, message=Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or another valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project., status=UNAUTHENTICATED}}
有人可以指出正确的方向,在那里我可以找到一些文档如何在Google Apps脚本中使用Google Docs API。
如果您拥有该文档,则无需使用API密钥。此外,您可以使用内置的Basic
OAuth令牌,而不是使用Bearer
身份验证,如下所示:
/**
* Get `Document` resource object from Google Docs REST API.
*
* @param {String} docId - A Google Document Id
*
* @return {Document} A Document resource object.
*/
function getDocumentResouce(docId) {
return JSON.parse(UrlFetchApp.fetch(
"https://docs.googleapis.com/v1/documents/" + docId,
{
"headers": {
"Authorization":"Bearer " + ScriptApp.getOAuthToken()
}
}
)
);
}
注意:GET
是UrlFetchApp.fetch()
使用的默认HTTP请求方法,因此您无需在options对象中定义它。
附录
正如Tanaike在评论中所述,您需要手动将相关范围(除了已经启用的范围)添加到清单JSON中。
首先检查项目属性,通过菜单File > Project Properties > Scopes
获取现有范围列表。您需要将这些范围以及相关文档范围之一(listed in the documentation)添加到清单中。
以下链接提供了管理清单和范围所需的信息:
https://developers.google.com/apps-script/concepts/manifests