Blog Post‎ > ‎

Build a RESTFul Web Service/API Using Google App Scripts in 5 Minutes

posted May 8, 2016, 3:07 PM by Julian Zhu   [ updated May 17, 2016, 6:21 PM by Julian Zhu ]
There are many ways of building RESTful web Sevices & API. 

This tutorial shows you how to build one in an easy and quick way using Google Sites and App Scripts to serve API and use Google Sheets to serve data. 

Typical use is to serve public data services/API. 

Google oAuth 2.0 can be easily added without any coding. 

Step 1. Prepare Your Data


Create a Google Sheet in Google Drive and popular data. The highlighted part is the Google Sheet ID that you will use later to reference this sheet and retrieve data. 



Step 2. Create a Google Site (https://sites.google.com)

If you don't know how to create a Google Site, you may read some other quick guide on the Internet. 


Step 3. Go to Google Site Edit Mode


From the drop down, select "Manage site". 


Step 4. Click "Apps Scripts" 




Step 5. Create a new Google Apps Script by clicking "Add new script". 

Your existing scripts are listed here so that you can always come back and edit them. 


Step 6. Now, you can start writing your first Google Apps Script. 


If you know JavaScript, coding is very straightforward. 


Step 7. Let's Copy & Paste my sample code

Company Ticker API
 
/*** main HTTP (GET and POST) interaction *************************/

function doGet(e) {
  return doPost(e);  
}

function doPost(e) {
 
  var apiKey = e.parameters.apiKey; 
  var operation = e.parameters.operation;
  var args = e.parameters.args; 
  var response;
  
  if(!validateKey(apiKey)) {
    response = sendFailResponse("500", "Fail - Invalid API Key");
  } else {
    if(operation == 'GetTickers') {
      response = GetTickers(); 
    } else {
      response = sendFailResponse("500", "Fail - operation not supported");
    }
  }
  return ContentService.createTextOutput(JSON.stringify(response))
    .setMimeType(ContentService.MimeType.JSON);
}

/********************* API Services ***********************************/
// Validate API Key
function validateKey(apiKey) {
  return (apiKey == '123456');
}

// Send failure response with code/message
function sendFailResponse(code, message) { 
  return {
      status: {
        code: code,
        message: message
      },
      payload: {
      }      
    };  
}

function GetTickers() {
  return {
    status: {
      code: "200",
      message: "Success"
    },
    payload: loadTickets()
  };
}


/********************** SHEET Transactions *****************************/
function getMasterSheetID() {
  return "34Vp54TdfVnO547R3N843olkrzJm2Vtza4JZIw6h8Wu33D"; // this is the sheet we created earlier
}

function loadTickets() {
  var objs = new Array(); 
  var spreadSheet = SpreadsheetApp.openById(getMasterSheetID()); 
  var sheet = spreadSheet.getActiveSheet(); 
  var data = sheet.getDataRange().getValues(); 
  // start from row 1
  for(var i=1; i < data.length; i++) {
    var obj = {
      ticker: data[i][0], 
      name: data[i][1]
    };
    objs.push(obj);
  }
  return objs;
}





Step 8. Save the Scripts. 


You may click "Run" and select methods to test run. 
Some method (e.g. doPost()) may depend on request parameters, and it may report error -- don't worry. We will test the API soon. 

Once we are ready to deploy and test, we may click "Publish" for testing. See next step on "Publish". 


Step 9. Publish API



Select appropriate permission to publish API script. In order for the API being used publicly, you may follow the similar permission on the example below. 


Follow the screen to authorize the publishing. 



Step 10. Congratulations! You just published a RESTFul API. 



To test the API: Copy the API URL from above and append it with a valid operation parameter: 

https//script.google.com/macros/s/AKfy.........?apiKey=123456&operation=GetTickers

Tip: Please use HTTP Post in your API client code. 

If you don't append appropriate API key or operation, you will get an failed response message. 

Enjoy!

About The Author

Julian Zhu is a principal consultant and managing partner at OSC Technologies  at the Great Boston area. He previously worked at CVS Health managing Enterprise Architecture team, and consultant at Greenwich Technology Partners. Contact him at julian.zhu@oscgc.com if you have any question. Thank you.