Search code examples
google-apps-scriptgoogle-cloud-platformgoogle-cloud-storagehttp-post

App Script: write a CSV file to a Google Cloud Storage Bucket


I have written an App Script that pulls data from a Big Query table in project A and is then supposed to write this data as a CSV to a Google Cloud Storage Bucket in project B. The former works but the latter fails. I have Cloud Storage Object Admin rights in project B but still get the following error when I run my script:

"error": {
    "code": 403,
    "message": "Insufficient Permission",
    "errors": [
      {
        "message": "Insufficient Permission",
        "domain": "global",
        "reason": "insufficientPermissions"
      }
    ]
  }

My script currently looks like this:

function pushCSV2Bucket(sheet_data){
  var bucketName = "some_name";
  var fileName = "wooqer_employee_details.csv";
  var csv_payload = sheet_data.map(row=>row.join(',')).join('\n');
  var url = "https://www.googleapis.com/upload/storage/v1/b/" + bucketName + "/o?uploadType=media&name=" + fileName;
  var options = {
                 method: "post",
                 contentType: "text/csv",
                 payload: csv_payload,
                  headers: {
                            Authorization: "Bearer " + ScriptApp.getOAuthToken(),
                           "Content-Type": "text/csv"
                           }
                };
  try {
    var response = UrlFetchApp.fetch(url, options);  // This will raise error if failed
    Logger.log('Successfully pushed CSV to GCS bucket : '+response.getContentText());
    return true;
  } catch (error) {
    Logger.log("Failed to push CSV to GCS bucket: " + error);
    return false;
  }
}

Do you perhaps know what is incorrect? I do not think the issue lies with the script. Perhaps, I cannot access to projects at a time when using App Script.


Solution

  • Answering this as community wiki .As you were able to resolve the issue by adding the necessary scopes to the appsscript.json file.

    To grant access to particular services and resources when using Google APIs in Apps Script, you must explicitly declare the relevant scopes in the script manifest (appsscript.json).

    As mentioned in the document you shared Setting explicit scopes

    Apps Script automatically determines what scopes a script needs by scanning its code for function calls that require them. For most scripts this is sufficient and saves you time, but for published add-ons and web apps you must exercise more direct control of the scopes.