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 like this see the Excel liberation site

About brucemcp 225 Articles
I am a Google Developer Expert and decided to investigate Google Apps Script in my spare time. The more I investigated the more content I created so this site is extremely rich. Now, in 2019, a lot of things have disappeared or don’t work anymore due to Google having retired some stuff. I am however leaving things as is and where I came across some deprecated stuff, I have indicated it. I decided to write a book about it and to also create videos to teach developers who want to learn Google Apps Script. If you find the material contained in this site useful, you can support me by buying my books and or videos.

2 Comments

  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.

Comments are closed.