JavaScript Quickstart

Complete the steps described in the rest of this page, and in about five minutes you'll have a simple JavaScript application that makes requests to the Google Apps Script Execution API.

Prerequisites

To run this quickstart, you'll need:

  • Python 2.4 or greater (to provide a web server).
  • Access to the internet and a web browser.
  • A Google account with Google Drive enabled.
  • A target Apps Script to call with the API.

Step 1: Turn on the Google Apps Script Execution API

  1. Open your target Apps Script in the editor and select Resources > Developers Console Project.
  2. In the dialog that opens, click on the blue link (that starts with your script's name) at the top to open the console project associated with your script.
  3. The left sidebar should say API Manager. If it does not, click the icon in the upper-left to open a side panel and select API Manager. Select Overview in the left sidebar.
  4. In the search bar under the Google APIs tab, enter "Google Apps Script Execution API". Click the same name in the list that appears. In the new tab that opens, click Enable API.
  5. Click Credentials in the left sidebar.
  6. Select the Credentials tab, click the Create credentials button and select OAuth client ID.
  7. Select the application type Web application.
  8. In the Authorized JavaScript origins field, enter the URL http://localhost:8000. You can leave the Authorized redirect URIs field blank.
  9. Click the Create button.
  10. Take note of the client ID in the resulting dialog. You will need it in a later step.
  11. Click OK to dismiss the resulting dialog.

Step 2: Set up the sample

Create a file named quickstart.html and copy in the following code:

<html>
  <head>
    <script type="text/javascript">
      // Your Client ID can be retrieved from your project in the Google
      // Developer Console, https://console.developers.google.com
      var CLIENT_ID = '<YOUR_CLIENT_ID>';

      var SCOPES = ['https://www.googleapis.com/auth/drive'];

      /**
       * Check if current user has authorized this application.
       */
      function checkAuth() {
        gapi.auth.authorize(
          {
            'client_id': CLIENT_ID,
            'scope': SCOPES.join(' '),
            'immediate': true
          }, handleAuthResult);
      }

      /**
       * Handle response from authorization server.
       *
       * @param {Object} authResult Authorization result.
       */
      function handleAuthResult(authResult) {
        var authorizeDiv = document.getElementById('authorize-div');
        if (authResult && !authResult.error) {
          // Hide auth UI, then load client library.
          authorizeDiv.style.display = 'none';
          callScriptFunction();
        } else {
          // Show auth UI, allowing the user to initiate authorization by
          // clicking authorize button.
          authorizeDiv.style.display = 'inline';
        }
      }

      /**
       * Initiate auth flow in response to user clicking authorize button.
       *
       * @param {Event} event Button click event.
       */
      function handleAuthClick(event) {
        gapi.auth.authorize(
          {client_id: CLIENT_ID, scope: SCOPES, immediate: false},
          handleAuthResult);
        return false;
      }

      /**
       * Calls an Apps Script function to list the folders in the user's
       * root Drive folder.
       */
      function callScriptFunction() {
        var scriptId = "ENTER_YOUR_SCRIPT_ID_HERE";

        // Create an execution request object.
        var request = {
            'function': 'getFoldersUnderRoot'
            };

        // Make the API request.
        var op = gapi.client.request({
            'root': 'https://script.googleapis.com',
            'path': 'v1/scripts/' + scriptId + ':run',
            'method': 'POST',
            'body': request
        });

        op.execute(function(resp) {
          if (resp.error && resp.error.status) {
            // The API encountered a problem before the script
            // started executing.
            appendPre('Error calling API:');
            appendPre(JSON.stringify(resp, null, 2));
          } else if (resp.error) {
            // The API executed, but the script returned an error.

            // Extract the first (and only) set of error details.
            // The values of this object are the script's 'errorMessage' and
            // 'errorType', and an array of stack trace elements.
            var error = resp.error.details[0];
            appendPre('Script error message: ' + error.errorMessage);

            if (error.scriptStackTraceElements) {
              // There may not be a stacktrace if the script didn't start
              // executing.
              appendPre('Script error stacktrace:');
              for (var i = 0; i < error.scriptStackTraceElements.length; i++) {
                var trace = error.scriptStackTraceElements[i];
                appendPre('\t' + trace.function + ':' + trace.lineNumber);
              }
            }
          } else {
            // The structure of the result will depend upon what the Apps
            // Script function returns. Here, the function returns an Apps
            // Script Object with String keys and values, and so the result
            // is treated as a JavaScript object (folderSet).
            var folderSet = resp.response.result;
            if (Object.keys(folderSet).length == 0) {
                appendPre('No folders returned!');
            } else {
              appendPre('Folders under your root folder:');
              Object.keys(folderSet).forEach(function(id){
                appendPre('\t' + folderSet[id] + ' (' + id  + ')');
              });
            }
          }
        });
      }

      /**
       * Append a pre element to the body containing the given message
       * as its text node.
       *
       * @param {string} message Text to be placed in pre element.
       */
      function appendPre(message) {
        var pre = document.getElementById('output');
        var textContent = document.createTextNode(message + '\n');
        pre.appendChild(textContent);
      }

    </script>
    <script src="https://apis.google.com/js/client.js?onload=checkAuth">
    </script>
  </head>
  <body>
    <div id="authorize-div" style="display: none">
      <span>Authorize access to Google Apps Script Execution API</span>
      <!--Button for the user to click to initiate auth sequence -->
      <button id="authorize-button" onclick="handleAuthClick(event)">
        Authorize
      </button>
    </div>
    <pre id="output"></pre>
  </body>
</html>

Replace the placeholder <YOUR_CLIENT_ID> in the copied code with the client ID you created in Step 1. Be sure to also replace the placeholder ENTER_YOUR_SCRIPT_ID_HERE with the script ID of your target script.

Step 3: Run the sample

  1. Start the web server using the following command from your working directory:

Python 2.x

python -m SimpleHTTPServer 8000

Python 3.x

python -m http.server 8000

  1. Load the URL http://localhost:8000/quickstart.html into your browser.

The first time you run the sample, it will prompt you to authorize access:

  1. Click the Authorize button to open the authorization window.

    If you are not already logged into your Google account, you will be prompted to log in. If you are logged into multiple Google accounts, you will be asked to select one account to use for the authorization.

  2. Click the Accept button.

Notes

  • After the initial user authorization, calls to gapi.auth.authorize that use immediate:true mode will obtain an auth token without user interaction.

Further reading

Troubleshooting

Error: origin_mismatch

This error will occur during the authorization flow if the host and port used to serve the web page doesn't match an allowed JavaScript origin on your Google Developers Console project. Make sure you completed the Step 1.e and that the URL in your browser matches.

Send feedback about...

Apps Script
Apps Script