Search code examples
javascriptviewyoutube-data-api

How to get view count using youtube data api in javascript?


I was trying to get some data using Youtube data api -v3. All the data inside data.items.snippet is coming perfectly. But, rest of the data, for example data.items[0].statistics.viewCount cannot be retrieve. Here is my code:

<script src="https://apis.google.com/js/client.js?onload=handleClientLoad"></script>
<script>
$(document).ready(function () {

  var key = 'MY_API_KEY';
  var playlistId = 'PL6Oh0ejUo_0jJlgikR5CNH38O9NE5JDbK';
  var URL = 'https://www.googleapis.com/youtube/v3/playlistItems';

  var options = {
      part: 'snippet,statistics',
      key: key,
      maxResults: 20,
      playlistId: playlistId
  }

  loadVids();

  function loadVids() {
      $.getJSON(URL, options, function (data) {
          var id = data.items[0].snippet.resourceId.videoId;
          mainVid(id);
          resultsLoop(data);
      });
  }

  function mainVid(id,c) {
      $('#video').html(`
        <iframe width="420" height="250" src="https://www.youtube.com/embed/${id}" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>
      `);
  }


  function resultsLoop(data) {

      $.each(data.items, function (i, item) {
          var c = item.contentDetails.duration;

          var thumb = item.snippet.thumbnails.medium.url;
          var title = item.snippet.title;
          var desc = item.snippet.description.substring(0, 120);
          var vid = item.snippet.resourceId.videoId;


          $('main').append(`
            <article class="item" data-key="${vid}">

              <img src="${thumb}" alt="" class="thumb">
              <div class="details">
                <h4>${title}</h4>
                <p>${desc}</p>
                                <p>${published_at}</p>
                                <p>${c}</p>
              </div>

            </article>
          `);
      });
  }

  // CLICK EVENT
  $('main').on('click', 'article', function () {
      var id = $(this).attr('data-key');
      mainVid(id);
  });

});
</script>

At first part: 'snippet,statistics', this part was like part: 'snippet',


Solution

  • I finally could solve it. The code is like the following one:

    $(document).ready(function () {
    
      var key = 'ENTER_YOUR_KEY';
      var playlistId = 'ENTER_YOUR_PLAYLIST_ID';
      var URL = 'https://www.googleapis.com/youtube/v3/playlistItems';
        var URL2 = 'https://www.googleapis.com/youtube/v3/videos'
    
      var options = {
          part: 'snippet',
          key: key,
          maxResults: 20,
          playlistId: playlistId
      }
    
      loadVids();
    
      function loadVids() {
          $.getJSON(URL, options, function (data) {
              var id = data.items[0].snippet.resourceId.videoId;
              mainVid(id);
              resultsLoop(data);
          });
      }
    
    //THIS FUNCTION WILL USE THE VIDEO ID FROM PREVIOUS API CALL AND RETRIEVE VIEW COUNT
          function view_count(vid) {
                var opt = {
                        part: 'statistics',
                        key: key,
                        id: vid,
                }
                var vc = null;
    
              $.getJSON(URL2, opt, function (data) {
                  vc = data.items[0].statistics.viewCount;
                                $('#'+vid).append(`<p>Views: ${vc}</p>`);
              });
          }
    
      function mainVid(id) {
          $('#video').html(`
            <iframe width="420" height="250" src="https://www.youtube.com/embed/${id}" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>
          `);
      }
    
    
      function resultsLoop(data) {
    
          $.each(data.items, function (i, item) {
    
              var thumb = item.snippet.thumbnails.medium.url;
              var title = item.snippet.title;
              var desc = item.snippet.description.substring(0, 70);
              var vid = item.snippet.resourceId.videoId;
                        var view = view_count(vid); //CALL FOR VIEWS
                        console.log(view);
    
    
              $('main').append(`
                <article class="item" data-key="${vid}">
    
                  <img src="${thumb}" alt="" class="thumb">
                  <div class="details" id="${vid}">
                    <b>${title}</b>
                    <p>${desc}</p>
                  </div>
    
                </article>
              `);
          });
      }