Making a GET request via UrlFetchApp.fetch in Google Apps Script returns a 401 Truncated Server Response error, but only when running in the editor/browser window.
I have the following code in Google Apps Script, which makes API calls to one of our vendors:
function test() {
//Get session ID from vendor. This always works.
var sesResponse = JSON.parse(UrlFetchApp.fetch("https://www2.pcrecruiter.net/rest/api/access-token/?Username=redacted&Password=redacted&DatabaseId=redacted.redacted&ApiKey=abcdefghijklmnopqrstuvwxyz&AppId=123456"));
sessionID = sesResponse.SessionId;
console.log("sessionID = " + sessionID);
//Make GET request to one of their API endpoints using acquired session ID. This returns a 401 Truncated Server Response
var response = JSON.parse(UrlFetchApp.fetch("https://www2.pcrecruiter.net/rest/api/candidates/?SessionID=" + sessionID + "&Query=MobilePhone%20co%201234567899&ResultsPerPage=100").getContentText());
console.log(response);
}
Acquiring the session ID is always successful. However, the second fetch request to the /candidates endpoint returns the following error:
Exception: Request failed for https://www2.pcrecruiter.net returned code 401. Truncated server response: {"errors":" at Microsoft.VisualBasic.ErrObject.Raise(Int32 Number, Object Source, Object Description, Object HelpFile, Object HelpContext)\r\n ... (use muteHttpExceptions option to examine full response)
On a whim I tried setting an "every minute" trigger to execute the exact same code above, and it ran flawlesssly. Our office's static IP as well as Google's official list of IPs (https://www.gstatic.com/ipranges/goog.txt) are all on the vendor's whitelist, so no requests should be blocked from either source.
Why would UrlFetchApp GET requests return a 401 error when executed from the browser/GAS editor only?