google-apps-scripturlfetchhttp-status-code-406

Google App Script external API return error 406


I'm trying to fetch a URL using optional advanced parameters in GAS:

function myFunction() {
  var options = {};
  options = {
    headers: {
      Authorization: 'Bearer ?????',
      'Content-Type': 'application/json',
    },
  };
  UrlFetchApp.fetch(<url>, options);
}

I always get:

Request failed for returned code 406 (line 52, file "Project").

HTTPResponse:

SyntaxError: Empty JSON string

I did the same fetching in Excel Power Query:

let
    Source = Json.Document(Web.Contents(<URL>, [Headers=[Authorization="Bearer 
?????????????", ContentType="application/json"]])),

And it works, it works also using Postman...

What's the problem with GAS? Please help me! Thanks in advance to everybody. Andrea


Solution

  • 406 error is because content negotiation between server and client has failed. While setting Content-Type, It's possible that the accepted return content is also advertised as 'application/json' by Power query and Postman, but UrlFetchApp doesn't do the same. Adding a explicit Accept header solves this:

    Accept: 'application/json'
    

    References: