0

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?

Scott
  • 15
  • 4
  • Although I cannot test your script and I'm not sure whether your situation is related, is your situation related to these threads? https://stackoverflow.com/q/63024346 and https://stackoverflow.com/q/70118777 – Tanaike Sep 01 '23 at 00:15
  • @Tanaike thanks for those suggestions, though they unfortunately did not answer my question. I experimented with sending a GET request via UrlFetchApp to https://httpbin.org/get in editor vs via trigger, though. The trigger execution lists only one URL in the 'origin' header (a Google IP), where as the editor execution lists two IP's (my office IP and then a random Google IP). Not sure if this could be affecting it at all, but that's the only difference I could spot. – Scott Sep 01 '23 at 13:52
  • Thank you for replying. I deeply apologize that my comment was not useful for your situation. – Tanaike Sep 02 '23 at 00:24

0 Answers0