{# Vars for auth docs %}

JavaScript Code Samples

The code sample below uses the Google APIs Client Library for JavaScript. You can download this sample from the javascript folder of the YouTube APIs code sample repository on GitHub.

The code requests the user's permission to access the https://www.googleapis.com/auth/yt-analytics.readonly scope.

return gapi.auth2.getAuthInstance()
    .signIn({scope: "https://www.googleapis.com/auth/yt-analytics.readonly"})
    ...

Your application might also need to request access to other scopes. For example, an application that calls the YouTube Analytics API and the YouTube Data API might need users to also grant access to their YouTube accounts. The authorization overview identifies scopes typically used in applications that call the YouTube Analytics API.

Retrieve daily channel statistics

This example calls the YouTube Analytics API to retrieve daily views and other metrics for the authorizing user's channel for the 2017 calendar year. The sample uses the Google APIs JavaScript client library.

Set up authorization credentials

Before running this sample locally for the first time, you need to set up authorization credentials for your project:

  1. Create or select a project in the Google API Console.
  2. Enable the YouTube Analytics API for your project.
  3. At the top of the Credentials 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. On the Credentials page, 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 from which you will be serving the code sample. For example, you could use something like http://localhost:8000 or http://yourserver.example.com. You can leave the Authorized redirect URIs field blank.
  7. Click the Create button to finish creating your credentials.
  8. Before closing the dialog box, copy the client ID, which you will need to put into the code sample.

Make a local copy of the sample

Then, save the sample to a local file. In the sample, find the following line and replace YOUR_CLIENT_ID with the client ID you obtained when setting up your authorization credentials.

gapi.auth2.init({client_id: 'YOUR_CLIENT_ID'});

Run the code

Now, you are ready to actually test the sample:

  1. Open the local file from a web browser, and open the debugging console in the browser. You should see a page that displays two buttons.
  2. Click the authorize and load button to launch the user authorization flow. If you authorize the app to retrieve your channel data, you should see the following lines print to the console in the browser:
    Sign-in successful
    GAPI client loaded for API
  3. If you see an error message instead of the lines above, confirm that you are loading the script from the authorized redirect URI that you set up for your project and that you put your client ID into the code as described above.
  4. Click the execute button to call the API. You should see a response object print to the console in the browser. In that object, the result property maps to an object that contains the API data.

Sample code

<script src="https://apis.google.com/js/api.js"></script>
<script>
  function authenticate() {
    return gapi.auth2.getAuthInstance()
        .signIn({scope: "https://www.googleapis.com/auth/yt-analytics.readonly"})
        .then(function() { console.log("Sign-in successful"); },
              function(err) { console.error("Error signing in", err); });
  }
  function loadClient() {
    return gapi.client.load("https://youtubeanalytics.googleapis.com/$discovery/rest?version=v2")
        .then(function() { console.log("GAPI client loaded for API"); },
              function(err) { console.error("Error loading GAPI client for API", err); });
  }
  // Make sure the client is loaded and sign-in is complete before calling this method.
  function execute() {
    return gapi.client.youtubeAnalytics.reports.query({
      "ids": "channel==MINE",
      "startDate": "2017-01-01",
      "endDate": "2017-12-31",
      "metrics": "views,estimatedMinutesWatched,averageViewDuration,averageViewPercentage,subscribersGained",
      "dimensions": "day",
      "sort": "day"
    })
        .then(function(response) {
                // Handle the results here (response.result has the parsed body).
                console.log("Response", response);
              },
              function(err) { console.error("Execute error", err); });
  }
  gapi.load("client:auth2", function() {
    gapi.auth2.init({client_id: 'YOUR_CLIENT_ID'});
  });
</script>
<button onclick="authenticate().then(loadClient)">authorize and load</button>
<button onclick="execute()">execute</button>