GET and POST Requests in Google Apps Script

G
Published in: Google Apps Script

With Google Apps Script, you can easily create a Web App that serves HTML, JSON, XML or plain text output using the HTML service. When published as an app, the script gets a public URL that can be called using either GET or POST requests with parameters.

When publishing the script as a web app, make sure to allow anonymous access and execute the script as yourself. If you edit the script, always update the version and deploy the latest version.

Here is a basic Google Script that calls the app using the URL Fetch service and returns the parameters as JSON string.

function doGet(e) {

  if(typeof e !== 'undefined')
    return ContentService.createTextOutput(JSON.stringify(e.parameter));

}

function doPost(e) {

  if(typeof e !== 'undefined')
    return ContentService.createTextOutput(JSON.stringify(e.parameter));

}

function testPOST() {

  var url = ScriptApp.getService().getUrl();

  var payload =
      {
        "name" : "labnol",
        "blog" : "ctrlq",
        "type" : "post",
      };

  var options =
      {
        "method"  : "POST",
        "payload" : payload,
        "followRedirects" : true,
        "muteHttpExceptions": true
      };

  var result = UrlFetchApp.fetch(url, options);

  if (result.getResponseCode() == 200) {

    var params = JSON.parse(result.getContentText());

    Logger.log(params.name);
    Logger.log(params.blog);

  }

}

function testGET() {

  var queryString = "?name=labnol&blog=ctrlq&type=get";

  var url = ScriptApp.getService().getUrl() + queryString;

  var options =
      {
        "method"  : "GET",
        "followRedirects" : true,
        "muteHttpExceptions": true
      };

  var result = UrlFetchApp.fetch(url, options);

  if (result.getResponseCode() == 200) {

    var params = JSON.parse(result.getContentText());

    Logger.log(params.name);
    Logger.log(params.blog);

  }
}
Published in: Google Apps Script

Looking for something? Find here!

Meet the Author

Web Geek, Tech Columnist
A
Amit Agarwal

Amit Agarwal is a Google Developer Expert in GSuite and Google Apps Script. He holds an engineering degree in Computer Science (I.I.T.) and is the first professional blogger in India. Read more on Lifehacker and YourStory

Get in touch