G Suite Business customers can preview App Maker. Ask your domain admin to apply for early access.

Tutorial 6: Call an External Service

Button Widget Intermediate App Maker skills

access_time About 10 minutes

What you’ll build

You’ll build an app that fetches a stock quote (from the Google Finance service). The app uses both client scripts and a server script.

What you’ll learn

This tutorial teaches you how to:

  • Create a client script
  • Create a server script
  • Call an external service

Create your app

  1. Sign in to the G Suite account provided by your employer or school.
  2. Open App Maker.
  3. Create a blank app:
    • If App Maker displays the welcome dialog, click Create New App.
    • Otherwise, click Menu menu chevron_right New chevron_right Blank Application.
  4. Rename the app. Delete the default name, Untitled App, and enter Stock Quotes.

Create the UI

You’ll build a page that looks like this:

Stock Quote

To create this UI:

  1. Rename the page:

    1. Hover over NewPage and click Moremore_vertchevron_rightRename.
    2. Enter QuotesPage and click OK.
  2. Add an input widget for the stock symbol:

    1. Click Widgets and drag a Text Box Text Box Widget near the top-left corner of the canvas. In the Property Editor, the exact placement is visible under Layout.
    2. Increase the length of the text box. With the text box selected, on the right edge of the text box, drag the handle to the right.
    3. In the Property Editor, change the name property of the text box to StockSymbol and type Enter a stock symbol as the label property.
  3. Add a button for the user to click:
    1. From Widgets , drag a Button Button Widget onto the canvas to the right of the text box. Vertically align the bottom edges of the button and the text box.
    2. Double-click the button and rename it to Get Quote.
  4. Define an action to take when a user clicks the button:
    1. Click Get Quote.
    2. In the Property Editor chevron_right Button section, click the onClick property and select Custom Action.
    3. Use JavaScript to define the action. In the Client Script dialog, enter or copy and paste this script:
      getQuote();
    4. Press Esc to close the dialog.
  5. Add a Label widget for the output:
    1. From Widgets , drag a Label Label Widget onto the canvas below the text box.
    2. In the Property Editor, set the name property to QuoteOutput and the text property to No quote retrieved.
  6. Click Close close to close Widgets.

Learn about the scripts the app will use

The app you’re creating is complete, except for the JavaScript functions needed to get stock quotes. In this step, you’ll copy and paste the functions that your app needs into scripts in your app. Scripts are containers in App Maker that are similar to script files:

  • Client script—Contains JavaScript that the browser’s JavaScript engine runs.
  • Server script—Contains JavaScript that a JavaScript engine on the App Maker server runs.

This flowchart illustrates what the scripts do:

Styling Flow Chart

Script functions

Client scripts:

  • extractPrice—Extracts the price from the server response and formats it.
  • getQuote—This function:
  • Responds to a button click and passes the entered stock symbol to the fetchStockQuote server script.
  • Uses a callback function to receive the response from the fetchStockQuote server script.
  • Calls the extractPrice client script.
  • Updates the UI with the stock quote, or with an error message if the stock quote was unavailable.

Server script:

  • fetchStockQuote—Calls the external service that provides the current stock price, and returns that result to the calling script.

Create a client script

  1. Create a client script to contain the functions that the client will run.
    1. Hover over Scripts and click add to add a script.
    2. When the Create script dialog appears, leave Client selected, uncheck Generate sample code, and click Create.
  2. Rename the client script:
    1. In the left sidebar, hover over NewScript and click Moremore_vertchevron_rightRename.
    2. Enter ClientScript and click OK.
  3. Copy and paste this JavaScript into ClientScript:
     
    function extractPrice(result) {
      var resultJSON = JSON.parse(result.replace("//"," "));
      var quoteString = resultJSON[0]["t"] + ": " +
          resultJSON[0]["l"] + " (" +
          resultJSON[0]["e"] + ", "  +
          resultJSON[0]["ltt"] + ")";
          return quoteString;
    }
    function getQuote() {
      var page = app.pages.QuotesPage;
      var symbol = page.descendants.StockSymbol.value;
      var stockQuote = page.descendants.QuoteOutput;
      stockQuote.text = "Fetching...";
      google.script.run
        .withFailureHandler(function(error) {
          // An error occurred, so display an error message.
          stockQuote.text = "Unable to retrieve stock quote!";
       })
       .withSuccessHandler(function(result) {
         // Format the quote and display it.
         var stockPrice = extractPrice(result);
         stockQuote.text = stockPrice;
       })
       .fetchStockQuote(symbol);
    }
    How does this script work?
  4. In the getQuote function, note the following references to App Maker objects and properties:
        var page = app.pages.QuotesPage;
        var symbol = page.descendants.StockSymbol.value;
        var stockQuote = page.descendants.QuoteOutput;
        
    Note the following about these references:
    • Use JavaScript dot notation to reference objects in the object hierarchy of an app and to reference properties of objects.
    • Reference the QuotesPage object relative to the top-level app object.
    • Reference the StockSymbol and QuoteOutput objects relative to QuotesPage as descendants of that page. You don’t need to specify the object hierarchy from the QuotesPage object down to the other objects.
    • If you change the object hierarchy, for example, by dragging these objects into a panel, you don’t need to modify the JavaScript.
    • Reference the property of an object relative to the object (for example, StockSymbol.value), but you must still reference that object relative to the top-level app object.

Create a server script

  1. Create a server script to contain the function that the server will run:
    1. Hover over Scripts and click add to add a script.
    2. When the Create Script dialog appears, click Server, leave Generate sample code unchecked, and click Create.
  2. Rename the server script:
    1. In the left sidebar, hover over NewScript and click More more_vert Rename.
    2. Enter ServerScript and click OK.
  3. Copy and paste this JavaScript into ServerScript:
     
    function fetchStockQuote(symbol) {
      var url = "http://www.google.com/finance/info?q=" + symbol;
      var response = UrlFetchApp.fetch(url);
      return response.getContentText();
    }
    How does this script work?

Preview and test your app

Preview your Stock Quotes app to see it in action.

  1. In the top-right corner, click Preview to run your app in a new browser tab.
  2. Click Allow to allow your app to use specific information.
  3. Enter a valid stock symbol (for example, GOOG) and click Get Quote. You’ll see Fetching… followed by the stock quote.
  4. Enter a stock symbol that’s invalid, or without first typing a stock symbol, click Get Quote. You’ll see Fetching… followed by Unable to retrieve stock quote.

Congratulations! You’ve just built an App Maker app that calls an external service.

Next steps

  1. Explore other applications in the App Maker Samples list.
  2. Find out more about this tutorial’s key concepts; for example: