Browser Quickstart

Complete the steps described in the rest of this page to create a simple browser application that makes requests to the Google Slides API.

Prerequisites

To run this quickstart, you need the following prerequisites:

  • Python 2.4 or greater (to provide a web server)
  • A Google account

Step 1: Turn on the Google Slides API

  1. Use this wizard to create or select a project in the Google Developers Console and automatically turn on the API. Click Continue, then Go to credentials.
  2. On the Add credentials to your project page, click the Cancel button.
  3. At the top of the page, select the OAuth consent screen tab. Select an Email address, enter a Product name if not already set, and click the Save button.
  4. Select the Credentials tab, click the Create credentials button and select OAuth client ID.
  5. Select the application type Web application.
  6. In the Authorized JavaScript origins field, enter the URL http://localhost:8000. You can leave the Authorized redirect URIs field blank.
  7. Click the Create button.
  8. Take note of the client ID in the resulting dialog. You need it in a later step.
  9. Click OK to dismiss the resulting dialog.
  10. Click the Create credentials button and select API key.
  11. Take note of the API key in the resulting dialog. You will need it in a later step.
  12. Click the Close button to create an unrestricted key. In production applications, you can restrict access to the API key to specific websites, IP addresses or mobile apps.

Step 2: Set up the sample

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

slides/quickstart/index.html
<!DOCTYPE html>
<html>
  <head>
    <title>Google Slides API Quickstart</title>
    <meta charset="utf-8" />
  </head>
  <body>
    <p>Google Slides API Quickstart</p>

    <!--Add buttons to initiate auth sequence and sign out-->
    <button id="authorize_button" style="display: none;">Authorize</button>
    <button id="signout_button" style="display: none;">Sign Out</button>

    <pre id="content" style="white-space: pre-wrap;"></pre>

    <script type="text/javascript">
      // Client ID and API key from the Developer Console
      var CLIENT_ID = '<YOUR_CLIENT_ID>';
      var API_KEY = '<YOUR_API_KEY>';

      // Array of API discovery doc URLs for APIs used by the quickstart
      var DISCOVERY_DOCS = ["https://slides.googleapis.com/$discovery/rest?version=v1"];

      // Authorization scopes required by the API; multiple scopes can be
      // included, separated by spaces.
      var SCOPES = "https://www.googleapis.com/auth/presentations.readonly";

      var authorizeButton = document.getElementById('authorize_button');
      var signoutButton = document.getElementById('signout_button');

      /**
       *  On load, called to load the auth2 library and API client library.
       */
      function handleClientLoad() {
        gapi.load('client:auth2', initClient);
      }

      /**
       *  Initializes the API client library and sets up sign-in state
       *  listeners.
       */
      function initClient() {
        gapi.client.init({
          apiKey: API_KEY,
          clientId: CLIENT_ID,
          discoveryDocs: DISCOVERY_DOCS,
          scope: SCOPES
        }).then(function () {
          // Listen for sign-in state changes.
          gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus);

          // Handle the initial sign-in state.
          updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get());
          authorizeButton.onclick = handleAuthClick;
          signoutButton.onclick = handleSignoutClick;
        }, function(error) {
          appendPre(JSON.stringify(error, null, 2));
        });
      }

      /**
       *  Called when the signed in status changes, to update the UI
       *  appropriately. After a sign-in, the API is called.
       */
      function updateSigninStatus(isSignedIn) {
        if (isSignedIn) {
          authorizeButton.style.display = 'none';
          signoutButton.style.display = 'block';
          listSlides();
        } else {
          authorizeButton.style.display = 'block';
          signoutButton.style.display = 'none';
        }
      }

      /**
       *  Sign in the user upon button click.
       */
      function handleAuthClick(event) {
        gapi.auth2.getAuthInstance().signIn();
      }

      /**
       *  Sign out the user upon button click.
       */
      function handleSignoutClick(event) {
        gapi.auth2.getAuthInstance().signOut();
      }

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

      /**
       * Prints the number of slides and elements in a sample presentation:
       * https://docs.google.com/presentation/d/1EAYk18WDjIG-zp_0vLm3CsfQh_i8eXc67Jo2O9C6Vuc/edit
       */
      function listSlides() {
        gapi.client.slides.presentations.get({
          presentationId: '1EAYk18WDjIG-zp_0vLm3CsfQh_i8eXc67Jo2O9C6Vuc'
        }).then(function(response) {
          var presentation = response.result;
          var length = presentation.slides.length;
          appendPre('The presentation contains ' + length + ' slides:');
          for (i = 0; i < length; i++) {
            var slide = presentation.slides[i];
            appendPre('- Slide #' + (i + 1) + ' contains ' +
                slide.pageElements.length + ' elements.')
          }
        }, function(response) {
          appendPre('Error: ' + response.result.error.message);
        });
      }

    </script>

    <script async defer src="https://apis.google.com/js/api.js"
      onload="this.onload=function(){};handleClientLoad()"
      onreadystatechange="if (this.readyState === 'complete') this.onload()">
    </script>
  </body>
</html>

Replace the placeholder <YOUR_CLIENT_ID> in the copied code with the client ID you created in Step 1. Likewise, replace the placeholder <YOUR_API_KEY> with the API key you created.

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 into your browser.

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

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

    If you're not already logged in to your Google account, the window prompts you to log in. If you are logged in to multiple Google accounts, you must 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 obtain an auth token without user interaction.

Further reading

Troubleshooting

Error: origin_mismatch

This error occurs 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 set an authorized JavaScript origin and that the URL in your browser matches the origin's URL.

idpiframe_initialization_failed: Failed to read the 'localStorage' property from 'Window'

The Google Sign-in library requires that 3rd party cookies and data storage is enabled in the web browser. For users that run into this error, prompt them to enable the feature or add an exception for accounts.google.com.

idpiframe_initialization_failed: Not a valid origin for the client

The Google Sign-in library requires that the domain registered in the Google Developers Console matches the domain being used to host the web page. Ensure that the origin you registered matches the URL in the browser.

Send feedback about...

Need help? Visit our support page.