Creating REST services with Google Apps Script

There are times when you'd like to create a service, want the service to be available publicly, and want to do this quickly, maybe for testing or for a demo you're putting together. In those cases, Google Apps Script might just be the solution you're looking for.

As an example, let's create a service that tells us if a number it receives is even. The number will be passed as a request parameter, e.g. ...?number=42, and will provide an XML response, e.g. <result>true</result>. Then, we will call this service from a form created with Form Builder, to show, next to an input field, whether the typed number is even or odd. Let's start by creating and deploying the service:

  1. To create a new script, load Google Drive, click on Create, and under More, choose Script. Click on Untitled project, and name it IsEven.

  2. Edit your script, or in this case copy-pate the following code in the editor:

    function doGet(request) {
        var result = '' + (request.parameter.number % 2 == 0) + '';
        return ContentService.createTextOutput(result)
            .setMimeType(ContentService.MimeType.XML);
    }

  3. To deploy your service, make sure it is first saved, then go to File | Manage Versions, click on Save New Version, and click OK to close the dialog. Go to Publish | Deploy as web app…, in Who has access to the app choose Anyone even anonymous, click Deploy. Copy and save somewhere the URL given to you in the following dialog: this is the URL of your script.

  4. Test the service by pasting the URL in a new tab of your browser and adding ?parameter=42. The service should respond <result>true</result>.

Now let's call the service from a form we create with Form Builder:

  1. In Form Builder, create a new form, create an input field, type a label and name it number, create and output field, type a label and name it even. Your form might look like:

  2. Define an HTTP service, by clicking on Add under HTTP Service in the sidebar. Name the service is-even, in Resource URL paste the URL from step 3 above. Under Serialization, choose HTML form. In Request Body enter <number/>.

  3. Define a action, by clicking on Add under Actions in the sidebar. Name it check-even, under React To choose Value Change, under Control choose number, in Service to call to choose is-even. In Set Service Request Values click the plus icon choose number and type /number, in Destination Control choose even and type /result.

  4. Test the form by clicking on the Test button. Type 42 and hit enter: the output next to it should show true. Type 43 and hit enter: similarly the output should show false.

Congratulations, you just created a service and a form calling that service, and all this without leaving your web browser.