Google app script can be a very useful tool when it comes to testing and automating a UI less application.This blog will help you to use Google App scripts to automate the API testing and its use cases.

GAS (Google App script) can be used with any of the API format be it SOAP, REST or the GraphQL.The below mentioned approach will make your testing much easier and scalable while using the GAS.

Use of Spreadsheet :

GAS provides a very handy support for other Google products and google's spreadsheets is one of them.

At one hand spreadsheet can be used to maintain the test data, On the other hand sheet can be integrated with desired menu options like given in the image below.

To Perform this open a new spreadsheet and go to tools and click on script editor. A new GAS will open.

Paste the below code into the script file

function onOpen(){
  Logger.log(SpreadsheetApp.getActiveSpreadsheet().getId());
  var ui = SpreadsheetApp.getUi();
  ui.createMenu('Test Menu').addItem("Run First Function", "functionName").addItem("Run Second Function", "secondFunction").addToUi();  
}

Defining the test data :

Spreadsheets can be used for any type of testing framework. eg.

  1. Test Data driven framework
  2. Keyword driven framework
  3. Hybrid framework

A typical sheet with the test data looks like

In case of keyword driven testing any parameter can be defined in the test data that can be used a key to call various use cases of the code.

URLFetchApp :

Furthermore, the most useful function that GAS provides to be used for calling the APIs(REST, SOAP and GraphQL) is UrlFetchApp.fetch(endpoint, options)

This function returns the response of the API which can further be parsed in the desired format and can be used for validations of the use cases.

function callApi(service, payload) {
  var response = "";
  var query =JSON.stringify({"query": payload});  
  var headers = {
    "Content-Type" : "application/json",
    "cookie" : cookie    
  }; 
  var options = {
    "method" : "POST", 
    "payload" : query,
    "headers" : headers,
    "muteHttpExceptions" : true,
    "followredirects":true
  };
  var endPoint = "<https://endpoint.com>";
  
  try{
    response = UrlFetchApp.fetch(endPoint, options)   
    Logger.log(response);
    var jsonR = JSON.parse(response)
    return jsonR
  }
  catch(error){
    return error.message;
  }
  
}

You can also make use of cookies in all requests and responses which will be discussed in our next chapter.

Keep Coding!!!