@Franzi suggested using undocumented approach which works and does not require making a donor/source spreadsheet public. Here’s how you can do it from Google App Script:
function addImportrangePermission() {
// id of the spreadsheet to add permission to import
const ssId = SpreadsheetApp.getActiveSpreadsheet().getId();
// donor or source spreadsheet id, you should get it somewhere
const donorId = '1GrELZHlEKu_QbBVqv...';
// adding permission by fetching this url
const url = `https://docs.google.com/spreadsheets/d/${ssId}/externaldata/addimportrangepermissions?donorDocId=${donorId}`;
const token = ScriptApp.getOAuthToken();
const params = {
method: 'post',
headers: {
Authorization: 'Bearer ' + token,
},
muteHttpExceptions: true
};
UrlFetchApp.fetch(url, params);
}
Usually there is no need, but in some rare cases you might want to add the required oauthScopes in appscript.json
manifest:
...,
"oauthScopes": [
"https://www.googleapis.com/auth/spreadsheets",
"https://www.googleapis.com/auth/script.external_request"
],
...