Advanced Google services

Advanced Google services

22.Sep.2021

    1.

            Google Cloud Vision API key requested to work with the Google Advanced Services.

            For this working example, I have not requested a paid account for this service.

            The first time it's run, it will prompt you to authenticate via OAuth2 using your Google Account Credentials.

I am using Apps Script web app so you would use your Apps Script project id instead of the email address associated with your personal gmail account or other google account e-mail used here. If you are familiar with developing on the server side of things, name the consumers of these services properly where italicized in this article within angle brackets (< >), i.e.: <MY_CLIENT_ID>

2.

            Google Calendar API key requested to work with the Google Advanced Services.

            For this working example, I have not requested a paid account for this service.

            The first time it's run, it will prompt you to authenticate via OAuth2 using your Google Account Credentials.

I am using Apps Script web app so you would use your Apps Script project id instead of the email address associated with your personal gmail account or other google account e-mail used here. If you are familiar with developing on the server side of things, name the consumers of these services properly where italicized in this article within angle brackets (< >), i.e.: <MY_CLIENT_ID>

3.

            Google Translate API key requested to work with the Google Advanced Services.

            For this working example, I have not requested a paid account for this service.

            The first time it's run, it will prompt you to authenticate via OAuth2 using your Google Account Credentials.

I am using Apps Script web app so you would use your Apps Script project id instead of the email address associated with your personal gmail account or other google account e-mail used here. If you are familiar with developing on the server side of things, name the consumers of these services properly where italicized in this article within angle brackets (< >), i.e.: <MY_CLIENT_ID>

3.1 Google Cloud Vision API: Example of advanced service

            Using the following example, I am going to show you how to use the Google Cloud Vision API in Apps Script and interact with other advanced services such as Gmail and Calendar.

            The example will consist of two Apps Script Web apps (or scripts), one for the client and one for the server side. The client will be a typical web app that we will call "VisionClient" which contains an HTML file and a JavaScript file. The JavaScript file is where we define our script functions that you would like to pass into your document via Apps Scripts (covered below). We could also put these functions directly inside the HTML if we wish, but we'll put them in a JavaScript file to keep the example simple.

            The server side will be a script that is called "VisionServer" and uses Google Cloud Vision API, but you could replace the advanced service with any of the supported services such as Gmail, Calendar, Drive, etc. We will call our Advanced Services from this webserver for our client using OAuth2 authentication and then return back JSON strings or data objects accordingly depending on what we would like to output. This way you can pass different requests into your Apps Script document and get back whatever data object it returns.

1st Example: VisionClient Webserver App

   <html>         <body>                    <h1>Welcome</h1>                    <hr>          <form method="POST">                <input type="text" name="query" placeholder="" />                <button onclick="getVisionList()">Get Vision</button>                 </form>          <div id='vision_list'></div>                    <script src='https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js'>             </script>                    <script src="/visionClientLibs/VisionClientLibrary-v1-0a4f640152c624838d15ff8ffb968ffd.js"></script>             </body>                    <script type="text/javascript">                    // VisionClientLibrary-v1-0a4f640152c624838d15ff8ffb968ffd library used for performing cloud vision api call and interacting with an advanced service such as Gmail or Calendar

        function getVisionList(){             $('#vision_list').html("");             var url = "https://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=";             var options = {                   query:$('form #query').val(),                                  language: "en"         };                $.getJSON(url+options, function(result){                   $('#vision_list').append("<ul>" + result + "</ul>");         }); //end getVisionList ���� } //end function getVisionList()                    $(document).ready(function(){ //start the code that will interact with Apps Script document below.......

                    var googApp = UiApp.createApplication();                    googApp.add(new Label("Please enter your query", Label.RIGHT));                    $('form').submit(function(){                     console.log('SUBMIT');                     googApp.add(new Label("Retrieving results...",Label.RIGHT));                         googApp.add(googApp.createHTML('

                        var script = document.createElement('script');                              script.textContent='VisionClientLibrary-v1-0a4f640152c624838d15ff8ffb968ffd';         }); //end submit()     //start the function that will be called from Apps Script below.......

      googApp.add(googApp.createInput("", "placeholder", InputType.TEXT_AUTO_COMPLETE).setWidth("200px"));            googApp.add(googApp.createButton("Get Vision", Button.OK));            googApp.add(googApp.createHTML("<br><div id='vision_result'></div>"+                      "</div>"));           //end of createInput and createButton function ...............

      var script = document.createElement('script');                              script.textContent='VisionClientLibrary-v1-0a4f640152c624838d15ff8ffb968ffd';         }); //end ready() ..........

            The Google Apps Script side will be our "VisionClient" which we named above and is where we define our functions to interact with the Advanced Services.

            We will start simply for this example and call our library from the webpage referenced above containing our user input. Our Apps Script document is contained in "VisionClientLibrary-v1-0a4f640152c624838d15ff8ffb968ffd" (version 1) and we need to copy that into Google Developer's Scripts HTML service which you can get by going to: https://script.google.com/htmlservice/category?ctag=VCL&category=vision

            This is where we'll paste in the library and then create a function called "getVisionList" which when called, simply gets us some JSON data back with one element in the list.

            The next thing we have to do is add our HTML containing the form and other elements which will be used by the webpage (please note that I've copy/pasted this from what you pasted above):

#vision_result {            width: 100%;        margin-top: 20px; }            #vision_list ul {      list-style: none;      margin: 0;      padding: 0; }            #vision_list li {     .....................} // end of styling

                    function getVisionList(){                    var script = UiApp.getActiveApplication().getScript();                                        script.execute("var googApp = UiApp.createApplication();");                    script.execute("googApp.add(new Label("Please enter your query", Label.RIGHT));");                    $('form').submit(function(){                     console.log('SUBMIT');         }); //end submit()  .......

                    var url = "https://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=";           var options = {                   query:$('form #query').val(),                                  language: "en"         };                $.getJSON(url+options,function(data){                         var response = JSON.parse(data);                                        googApp.add(new Label("Getting results...",Label.RIGHT));                                          googApp.add(googApp.createHTML('                     { //end of json data section

            The first line gets the library which you earlier copied into Developer's Scripts HTML service and then executes that script in this context (i.e., inside of our webpage). Retrieving the url request is simply retrieving the input value from the <input id="query" name="query"> element via JavaScript

                    After this we are creating another function called "getJSON" where we are executing the $.getJSON() Google Ajax method to get the data from calling out to the url for this example which is "https://ajax.googleapis.com/ajax/services/search/web?v=1.0&q="

                    The options variable contains simple parameters for querying Google's web service (url, language).

            The last block of code gets our response and parses it so we can access its properties via JavaScript (e.g., jsonData["responseData"]["results"]). This will be accessed through googApp which maps to our Apps Script code in Google Developer's Scripts HTML service that has the function called getVisionList().               

            The next thing we need to do is add a UI (User Interface) which will give us access to our input and show our output:

#vision_result {            width: 100%;        margin-top: 20px; }            #vision_list ul {      list-style: none;      margin: 0;      padding: 0; }            #vision_list li {     .....................} // end of styling

                    function getVisionList(){                    var script = UiApp.getActiveApplication().getScript();                                        script.execute("var googApp = UiApp.createApplication();");                    script.execute("googApp.add(new Label("Please enter your query",Label.RIGHT));");                    $('form').submit(function(){                     console.log('SUBMIT');         }); //end submit()  .......

                    var url = "https://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=";           var options = {                   query:$('form #query').val(),                                  language: "en"         };                $.getJSON(url+options,function(data){                         var response = JSONparse(data);                         googApp.add(new Label("Getting results...",Label.RIGHT));                         googApp.add(googApp.createHTML('                     { //end of json data section

                response["responseData"]["results"]                                            .forEach(function (item)                              {              var div = googApp.createHTML('                       <li>'+item.Title + ': '+item.URL);                             div.setStyleAttribute('class', 'result');                             div    .setStyleAttribute('style','padding: 2px 10px; margin-bottom: 5px');                             div.attachHTML('a','a:contains("Dog")')                              .setStyleAttribute('style', 'color:#4bb8f0');                             div.attachHTML('img','src:http://chart.apis.google.com/chart?chs=100x50&cht=qr&chl='+item["snippet"]);                               //this is to show the image only in the div                             googApp.add(div);                 }); // end of .forEach

           The next piece creates our UI which is mostly HTML with a little JavaScript borrowed from Stack Overflow user "leolower" (http://stackoverflow.com/users/4303296/leolower).    

                    The last section is the function googApp.createHTML which returns HTML from inside of Apps Script for us to add into our UI:

                 return $(googHTML); // end of createHTML()

                } /* end createHTML() */ }); // end jQuery Ajax call          

                Thats it in a nutshell! Try it out and enjoy the new functionality in Google Developer's Scripts! You can find more documentation on Advanced Services here . You might be wondering if this calls back to Google every time you run your code, well there are two factors to consider. One is that in Apps Scripts there are four apps included so this functionality wont slow down the whole service because it only runs in one of the 4 services. Secondly, when you run your code it will run inside a sandbox so no other script or users can see what's going on in another script because everything will be isolated to itself and not let out onto the rest of Apps Scripts!    

            The last thing we need to do is enable Advanced Services:

                        click on Enable and OK and you're done! You can Test via Google Cloud Console under Compute > Cloud Functions:           

Please note: This content is actually copied from its source - Stack Overflow user "danroth27" - https://stackoverflow.com/q/39477679 . It has been modified only to suit this blog's layout & its own purpose. If you see any content in this post that is yours and was not copied from Stack Overflow, please let us know by using the contact form on our Contact Us page so that we can give you credit for your work or remove it if requested! We do not intend to steal anyone's content in any way whatsoever. All information here in is free to use and distribute per a Creative Commons Attribution Share-Alike 3.0 License found at http://creativecommons.org/licenses/by-sa/3.0/. Thank you! :)

We are social