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.
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: