Google Apps Script UrlFetchApp returns 404 when th

2019-08-08 09:52发布

I'm trying to retrieve a pdf of a spreadsheet. Whenever I try I get the following error:

Request failed for https://docs.google.com/a/firstcallres.com/spreadsheets/d/1ZPcW5cOQT5w28VUbr_JG9U-r7m6Uf-MDQcSmFOyhbE8/export?exportFormat=pdf&format=pdf&size=letter&portrait=false&fitw=true&source=labnol&sheetnames=false&printtitle=false&pagenumbers=false&gridlines=false&fzr=false&gid=1680655368 returned code 404.

If I click on the above URL when signed in, a PDF downloads.

If I use the following code, I will get a login page back as a response. The URL is the sheet url, and the url_ext are the parameters.

var response = UrlFetchApp.fetch(url + url_ext);

If I then use the following code with an OAuth token, I get a 404 response.

  var response = UrlFetchApp.fetch(url + url_ext, {
          headers: {'Authorization': 'Bearer ' +  ScriptApp.getOAuthToken() }
          });

Why is this happening? How can I use a token to access the sheet through apps script to retrieve a PDF?

Edit: It has spontaneously started working on my test apps script. However, if I create the exact same function in another apps script it fails with a 404 error again.

I did some more troubleshooting, and copy-pasted the working function right into the new apps script project. That function ran successfully, afterwards the non-working function now works.

There were no edits done to the non-working function between it failing, and working.

Edit2: I can reproduce this error: If I take my 2nd working function, and copy - paste it into a new project it will fail with the 404 error. I don't know WHY this happens, but I can successfully reproduce the 404 error when it works somewhere else with the exact same code.

1条回答
Animai°情兽
2楼-- · 2019-08-08 10:54

You are missing the proper scopes to make this request. It should return a 401 unauthenticated instead of a 404. To fix this you need to add the Drive scope. I do this by a simple DriveApp.getRootFolder() call somewhere in your script. This will add the drive scope to your project. Any call to DriveApp will add the scope though.

Here is an example script:

function exportToPDF() {    
  var url = "https://docs.google.com/spreadsheets/d/1oQ2zsbcCwuc_wdwgfFopRJn-5fGN3oY7L237ivxuxmM/export?exportFormat=pdf"; //add your options as you wish
  var res = UrlFetchApp.fetch(url, {headers:{"Authorization":"Bearer " + ScriptApp.getOAuthToken()},muteHttpExceptions:true});
  var newPdf = Utilities.newBlob(res.getContent(), "application/pdf", "Export.pdf")
  DriveApp.createFile(newPdf);
}
查看更多
登录 后发表回答