Google Google Apps 脚本中的文档 API 作为外部 API(不是扩展服务)

Google Docs API in Google Apps Script as an external API (NOT as extended service)

我正在尝试通过 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 身份验证,您还可以利用内置的 Bearer OAuth 令牌,如下所示:

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

注意:GETUrlFetchApp.fetch()默认使用的HTTP请求方式,所以不需要在options对象中定义。


附录

正如评论中 Tanaike 所述,您需要手动将相关范围(除了您已经启用的范围)添加到您的清单 JSON。

首先检查您的项目属性以通过菜单获取现有范围的列表 File > Project Properties > Scopes。您需要将这些范围以及相关文档范围之一 (listed in the documentation) 添加到您的清单中。

以下链接提供了管理清单和范围所需的信息:

https://developers.google.com/apps-script/concepts/manifests

https://developers.google.com/apps-script/concepts/scopes