Working Title

Sat, May 23, 2020 3-minute read

Google Apps Script is a tool that solves problems without friction. You can abstract complex operations away in the higher level functions. It is easy to create a file with the DriveApp Class. If you need to add some properties, use the Advanced Drive Service. In the rare case that you need a specific call from the V3 api, use the UrlFetchApp and talk straight to the API. This all done using the online editor, serverless from start to finish. Usually Google Apps Script is on the left in the image below.

xkcd:Manuals

I use Google Apps Script often as middleware. Two systems can’t talk with each other,and Google Apps script can talk to both systems. A web App that is set to “Execute the app as me” will separate the user accessing the app from the user running the app. This way you can make controlled anonymous access possible.

Middleware can be implemented as an API. This is useful when you have a website that needs to perform an action that requires keeping secrets. In this article I will show the different options that are available in Apps Script to create an API. I will also deliberately ignore the documentation and show how Apps Script will help us through the process.

We will start with a simple api that will transform a text, it will make it lowercase and replace any spaces with hyphens.

2
3
4
5
6
7
8
// doGet will receive the GET HTTP request
function doGet(e) {
  // e.paramter contains the url parameters
  const par = e.parameter.par;
  const lowerAndHyphenated = par.replace(/\s+/g, '-').toLowerCase();
  return HtmlService.createHtmlOutput(lowerAndHyphenated);
}

From the Publish -> Deploy as web app the following dialog box can be openend:

Deploy as web app

Don’t publish the web app yet, use the “Test web app for your latest code.” option. This will show the first error message:

TypeError: HtmlService.createTextOutput is not a function (line 6, file “Code”).

So we have an error in line 6. We did not provide any url parameters. So we make the code bit more resillient:

 2
 3
 4
 5
 6
 7
 8
 9
10
11
// doGet will receive the GET HTTP request
function doGet(e) {
  // e.parameter contains the url parameters
  if(!e.parameter.par) {
    return HtmlService.createHtmlOutput("<b>please add a parameter to the url in the format ?par=[your data]</b>");
  }
  const par = e.parameter.par;
  const lowerAndHyphenated = par.replace(/\s+/g, '-').toLowerCase();
  return HtmlService.createHtmlOutput(lowerAndHyphenated);
}

Reload the page and it will show: please add a parameter to the url in the format ?par=[your data]

Add ?par=aaa%20BBB to the url. And now we have a working function.