Passing parameters to Google Apps Script as a Rest Server

In a previous post I covered how to use the Google Apps Script ScriptDB as a database from which to serve jSON responses – without the need for a server.

Of course you may need to pass arguments – here is how.

The server code (uses the rest Library) as input. If you pass the entry= parameter it will return a specific entry, otherwise the whole library will be returned.

function doGet(e) {
    var p = e.parameter ? e.parameter.entry : null;
    return ContentService
          .createTextOutput((p ?
               mcpher.getRestLibrary().child(p) :
               mcpher.getRestLibrary()).serialize())
          .setMimeType(ContentService.MimeType.JSON);
}

Directly at the browser with the entry= parameter. (no parameters returns the entire rest library)

https://script.google.com/a/macros/mcpher.com/s/AKfycbzLqpnQ2ey8CKAMmzchb2n2FU-aiae0iTKPzAOfAgEpxGwaJgk/exec?entry=e-sim

To Use from a script

function restTest() {
var j =
  UrlFetchApp.fetch(“https://script.google.com/a/macros/mcpher.com/s/AKfycbzLqpnQ2ey8CKAMmzchb2n2FU-aiae0iTKPzAOfAgEpxGwaJgk/exec?entry=e-sim”);
mcpher.DebugPrint(j.getContentText());
}

Returns

{“e-sim”:{“restType”:8001,”results”:””,”treeSearch”:true,”url”:”http://e-sim.org/apiMilitaryUnitMembers.html?id=”,”ignore”:””}}


For more stuff like this, visit Excel Liberation.

Author: brucemcp

2 thoughts on “Passing parameters to Google Apps Script as a Rest Server

  1. Like your example. It could only work for a service published as anonymous though. Any ideas how you might secure this to a Google Apps domain?

    I've tried it and it UrlFetch is going to fail because the doGet() needs an authenticated session cookie passed with the URL fetch (which it doesn't support). You don't really want to be passing username/passwords in a REST API if a user is already authenticated in GMail / Drive etc.

Leave a Reply

Your email address will not be published. Required fields are marked *