Encountering forbidden errors when updating public images in Google Docs via a service account. Code sample:
function sendApiReq(endpoint, dataObj) {
var auth = retrieveAuth();
auth.resetToken();
var response = UrlFetchApp.fetch(endpoint, {
method: 'POST',
headers: { Authorization: 'Bearer ' + auth.getToken() },
contentType: 'application/json',
payload: JSON.stringify(dataObj),
muteHttpExceptions: true
});
return JSON.parse(response.getContentText());
}
function buildImgUpdate(imgId, docId, tag) {
var updates = [];
var driveEndpoint = Utilities.formatString('https://www.googleapis.com/drive/v3/files/%s?supportsAllDrives=true&fields=webContentLink', imgId);
var driveResp = UrlFetchApp.fetch(driveEndpoint, { muteHttpExceptions: true });
var imgUrl = JSON.parse(driveResp.getContentText()).webContentLink;
var docsEndpoint = Utilities.formatString('https://docs.googleapis.com/v1/documents/%s?fields=inlineObjects', docId);
var docsResp = UrlFetchApp.fetch(docsEndpoint, { muteHttpExceptions: true });
var docData = JSON.parse(docsResp.getContentText());
for (var key in docData.inlineObjects) {
var caption = docData.inlineObjects[key].inlineObjectProperties.embeddedObject.title;
if (caption && caption === tag) {
updates.push({
updateImage: {
imageObjectId: key,
uri: imgUrl,
method: 'CENTER_CROP'
}
});
}
}
return updates;
}
var apiURL = 'https://docs.googleapis.com/v1/documents/YOUR_DOC_ID:batchUpdate';
var payload = { requests: buildImgUpdate('YOUR_IMAGE_ID', 'YOUR_DOC_ID', 'MERGE_FIELD') };
var result = sendApiReq(apiURL, payload);