How to download a file using a url in Google Apps Script

8.7k Views Asked by At

I am fairly new to Google Apps Script. I am using Google's functionality to access the DFA/DCM Trafficking and Reporting API through App Scripts without having to use OAuth.

When I run the DCM Report to then convert into google sheets, I am not able to figure out how to use either urls i'm supplied with to download the CSV.

Here is the code i'm using.

  var file =  DCM.Reports.run(profile.profileId,30792432);
  var file2 =  DCM.Files.get(30792432, file.id);
  //wait till running of the report is complete.
  file2 =  DCM.Files.get(30792432, file.id);
  var response = UrlFetchApp.fetch(file2.urls.browserUrl);

I also try using:

  file2.urls.apiUrl(); 

for the UrlFetchApp service, but that didn't work either.

Any help on how to execute the url to download the file as an object where I can paste into google sheets would be greatly appreciated.

1

There are 1 best solutions below

0
Gerneio On BEST ANSWER

Add the ScriptApp authorization bearer as a header in the parameters while using the apiurl call. Something like:

var token = ScriptApp.getOAuthToken();

var headersOptions = { 
  Authorization : 'Bearer '  + token
  };

var options = { 
  headers : headersOptions
  };

var csvDoc = UrlFetchApp.fetch(file2.url.apiurl, options);