Skip to content Skip to sidebar Skip to footer

Fetch Json Object From Google Webapp From Another Google Webapp

I have two Google Spreadsheets, each of which with some Apps Script attached. Eventually I want to deploy both as WebApps so they can communicate with one another through their pub

Solution 1:

When you deploy a script as a webapp to run as a service you can only use the .exec url to call it with urlFetch because the development url (the one ending with .dev) is only accessible by you and the request does not come from you but from Google.

I deployed your example and tested it with your code as follows :

functionpullJSON(URL) {  
  varURL = "https://script.google.com/macros/s/AKfycbzqRgv1XfUUrAimvD31OXx89GdhjeBd45SBODaq1c7bkGVusio/exec"var data = UrlFetchApp.fetch(URL, {"contentType": "application/json"});
Logger.log(data);
}

The result is as expected :

enter image description here

You can test it yourself since the app is deployed as "run as me" and accessible to anyone even anonymous.

If you want to restrict its access you'll have to add some parameters to the URL and handle these parameters in your server webapp to check the origin of the request.

Parameters are simply added to the url like this :

vardata = UrlFetchApp.fetch(URL+"?user=serge&secret=secretcode", {"contentType": "application/json"});

then in your server script check it like this :

var user = request.parameter.user;
var secret = request.parameter.secret;

and you'll get the user and secret.


EDIT : here is a complete example of both scripts with a security control :

webapp :

functiondoGet(e) {
  var data = [[1, 2, 3], [4, 5, 6]]; //dummy JSON object
  if(e.parameter.user=='serge'&&e.parameter.secret=='secretcode'){
    return ContentService.createTextOutput(JSON.stringify(data))
    .setMimeType(ContentService.MimeType.JSON);
  }else{
    return ContentService.createTextOutput('You are not allowed to get this result, user should be '+e.parameter.user+' and code should be '+e.parameter.secret)
    .setMimeType(ContentService.MimeType.TEXT);
  }
}

and test script :

function pullJSONSecure() {  
  var URL = "https://script.google.com/macros/s/AKfycbyzoFbcjTXMCALTOlscwAZP6gY1mWc1mkbWb84LYO-qeQk16xw/exec"var data = UrlFetchApp.fetch(URL+"?user=serge&secret=secretcode", {"contentType": "application/json"});
  Logger.log(data);
}

If you try this script and change the user name or the password you will see what happens.


EDIT 2 : deployment parameters :

enter image description here

Post a Comment for "Fetch Json Object From Google Webapp From Another Google Webapp"