简体   繁体   中英

Using Google Sheets API from within Apps Script for same Sheet

Using an Apps Script that's bound to a Spreadsheet to effect the sheet is very straight forward, via the SpreadsheetApp global. However, there's some functionality, such as getting/setting filters on a sheet, that can only be accessed from the Google Sheets REST API.

I've seen an example that uses UrlFetchApp from within an Apps Script, to call the Google Sheet API, but it's written as if the Apps Script is not actually bound to a particular Spreadsheet.

function getSheetBasicFilter(ssId, sheetId) {
  var params = {
    headers: {
      "Authorization": "Bearer " + ScriptApp.getOAuthToken()
    }
  };
  var base = "https://sheets.googleapis.com/v4/spreadsheets/";
  var partialRespParams = "?fields=sheets%2FbasicFilter";
  var resp = UrlFetchApp.fetch(base + ssId + partialRespParams, params);
  var sheets = JSON.parse(resp.getContentText()).sheets;
  for (var i = 0; i < sheets.length; i++) {
    if (sheets[i].basicFilter 
        && (sheets[i].basicFilter.range.sheetId == sheetId 
            || (!sheets[i].basicFilter.range.sheetId && sheetId == 0))) {
      return sheets[i].basicFilter;
    }
  }
  return null;
}

When I attempt to call this function from within a Spreadsheet Bound Apps Script, I get an error 'Request had insufficient authentication scopes'.

Since the script is running as the user that owns the document, and ScriptApp.getOAuthToken() is being used, it's not clear why this error is occurring.

Any help would be appreciated.

First, make sure you enable the Sheets API in your Developers Console.

The error " Request had insufficient authentication scopes " is an error in the OAuth 2.0 token provided in the request specifies scopes that are insufficient for accessing the requested data.

Make sure you use the correct and all necessary scopes , and check this Authorizing requests with OAuth 2.0 if you properly follow the steps here.

You can also try to revoke the access and try to redo it.

For more information, check the documentation of ScriptApp.getOAuthToken() and this thread

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM