Skip to content
Advertisement

Content Service for Google Apps Script returning HTML instead of JSON

Trying out the Content Service API and the example is returning HTML when it should be returning JSON, what am I doing wrong?

https://developers.google.com/apps-script/guides/content

function doGet(request) {
  var events = CalendarApp.getEvents(
    new Date(Number(request.parameters.start) * 1000),
    new Date(Number(request.parameters.end) * 1000));
  var result = {
    available: events.length == 0
  };
  return ContentService.createTextOutput(JSON.stringify(result))
    .setMimeType(ContentService.MimeType.JSON);
}

GAS from another file trying to make the request:

function myFunction() {
  var url = "published URL";
  url+="?start=1325437200&end=1325439000";

  var options = {
    method:"get"
  }
  var response = UrlFetchApp.fetch(url,options).getContentText();
  response = JSON.parse(response); //error, unexpected token <
}

Advertisement

Answer

Your usage of ContentService is correct, the code works exactly as is. Here is a link to my copy of your code published as a web app:

https://script.google.com/macros/s/AKfycbzx2L643LHw0oQAq1jBmKQh2ju_znGfmdj78dUypj36iF-s91w/exec

The problem you are running into is related to Authorization or Authentication, if the published script is not authorized, an HTML error message is returned.

To check if that is your issue, simply access the published URL directly in your browser. If you see JSON displayed, then Authorization is not the problem. If you see the “Authorization is required to perform that action” error message, open your published script and choose “doGet” from the Run menu, then follow the authorization prompts.

More likely, the problem is related to how your script is published. In order to access your published script from another script, it must be published with the “Who has access to the app” setting as “Anyone, Even anonymous“. If you use any other value, Google returns an HTML login page instead of your JSON response, and you get the error you are seeing.

This happens because requests sent from Google Apps Script via URLFetchApp are not authenticated, they don’t carry the credentials of the user running the code with them, and come in as anonymous requests.

If you don’t allow “Anyone, even anonymous” in your publishing settings, Google redirects non-authenticated requests to the Google login page.

Advertisement