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 YouTube Data API.

The sample code used in this guide retrieves the channel resource for the GoogleDevelopers YouTube channel and prints some basic information from that resource.

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.

Step 1: Turn on the YouTube Data 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 will need it in a later step.
  9. 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. In the code, replace the placeholder <YOUR_CLIENT_ID> with the client ID that you created in Step 1.

<!DOCTYPE html>
<html>
  <head>
    <title>YouTube Data API Quickstart</title>
    <meta charset='utf-8' />
  </head>
  <body>
    <p>YouTube Data 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"></pre>

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

      // Array of API discovery doc URLs for APIs used by the quickstart
      var DISCOVERY_DOCS = ["https://www.googleapis.com/discovery/v1/apis/youtube/v3/rest"];

      // Authorization scopes required by the API. If using multiple scopes,
      // separated them with spaces.
      var SCOPES = 'https://www.googleapis.com/auth/youtube.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({
          discoveryDocs: DISCOVERY_DOCS,
          clientId: CLIENT_ID,
          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;
        });
      }

      /**
       *  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';
          getChannel();
        } 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 text to a pre element in the body, adding the given message
       * to a text node in that element. Used to display info from API response.
       *
       * @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);
      }

      /**
       * Print files.
       */
      function getChannel() {
        gapi.client.youtube.channels.list({
          'part': 'snippet,contentDetails,statistics',
          'forUsername': 'GoogleDevelopers'
        }).then(function(response) {
          var channel = response.result.items[0];
          appendPre('This channel\'s ID is ' + channel.id + '. ' +
                    'Its title is \'' + channel.snippet.title + ', ' +
                    'and it has ' + channel.statistics.viewCount + ' views.');
        });
      }

    </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>

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.
  • The authorization flow in this example is designed for a JavaScript web application. For information on this authorization flow, see Using OAuth 2.0 for JavaScript Applications.

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. There are two common fixes for this error:

  • Make sure you completed Step 1.f and that the URL in your browser matches the URL listed as a valid origin.
  • Make sure that you replaced the text YOUR_CLIENT_ID in the code sample with the client ID that you obtained in step 1.h.

Enviar comentarios sobre…