[javascript] How to get number of video views with YouTube API?

The question is very simple. How to get number of video views with YouTube API?

enter image description here

The task is simple but I would like to use that query on large number of videos very often. Is there any way to call their Youtube API and get it? (something like facebook http://api.facebook.com/restserver.php?method=links.getStats&urls=developers.facebook.com)

This question is related to javascript youtube-api

The answer is


look at yt:statistics tag. It provides viewCount, videoWatchCount, favoriteCount etc.


Here is a small code snippet to get Youtube video views from URL using Javascript

Demo of below code

    function videoViews() {
var rex = /[a-zA-Z0-9\-\_]{11}/,
    videoUrl = $('input').val() === '' ? alert('Enter a valid Url'):$('input').val(),
    videoId = videoUrl.match(rex),
    jsonUrl = 'http://gdata.youtube.com/feeds/api/videos/' + videoId + '?v=2&alt=json',
   embedUrl = '//www.youtube.com/embed/' + videoId,
   embedCode = '<iframe width="350" height="197" src="' + embedUrl + '" frameborder="0" allowfullscreen></iframe>'


//Get Views from JSON
$.getJSON(jsonUrl, function (videoData) {
    var videoJson = JSON.stringify(videoData),
        vidJson = JSON.parse(videoJson),
        views = vidJson.entry.yt$statistics.viewCount;
    $('.views').text(views);
});

//Embed Video
$('.videoembed').html(embedCode);}

You can use this too:

<?php
    $youtube_view_count = json_decode(file_get_contents('http://gdata.youtube.com/feeds/api/videos/wGG543FeHOE?v=2&alt=json'))->entry->{'yt$statistics'}->viewCount;
    echo $youtube_view_count;
    ?>

Use the Google PHP API Client: https://github.com/google/google-api-php-client

Here's a little mini class just to get YouTube statistics for a single video id. It can obviously be extended a ton using the remainder of the api: https://api.kdyby.org/class-Google_Service_YouTube_Video.html

class YouTubeVideo
{
    // video id
    public $id;

    // generate at https://console.developers.google.com/apis
    private $apiKey = 'REPLACE_ME';

    // google youtube service
    private $youtube;

    public function __construct($id)
    {
        $client = new Google_Client();
        $client->setDeveloperKey($this->apiKey);

        $this->youtube = new Google_Service_YouTube($client);

        $this->id = $id;
    }

    /*
     * @return Google_Service_YouTube_VideoStatistics
     * Google_Service_YouTube_VideoStatistics Object ( [commentCount] => 0 [dislikeCount] => 0 [favoriteCount] => 0 [likeCount] => 0 [viewCount] => 5 )  
     */
    public function getStatistics()
    {
        try{
            // Call the API's videos.list method to retrieve the video resource.
            $response = $this->youtube->videos->listVideos("statistics",
                array('id' => $this->id));

            $googleService = current($response->items);
            if($googleService instanceof Google_Service_YouTube_Video) {
                return $googleService->getStatistics();
            }
        } catch (Google_Service_Exception $e) {
            return sprintf('<p>A service error occurred: <code>%s</code></p>',
                htmlspecialchars($e->getMessage()));
        } catch (Google_Exception $e) {
            return sprintf('<p>An client error occurred: <code>%s</code></p>',
                htmlspecialchars($e->getMessage()));
        }
    }
}

Why using any api key to retrieve a portion of public html!

Simplest unix command line demonstrative example, using curl, grep and cut.

curl https://www.youtube.com/watch?v=r-y7jzGxKNo | grep watch7-views-info | cut -d">" -f8 | cut -d"<" -f1

Yes, it get the full html page, this loss has no meaning against the countless advantages.


Here is a simple function in PHP that returns the number of views a YouTube video has. You will need the YouTube Data API Key (v3) in order for this to work. If you don't have the key, get one for free at: YouTube Data API

//Define a constant so that the API KEY can be used globally across the application    
define("YOUTUBE_DATA_API_KEY", 'YOUR_YOUTUBE_DATA_API_KEY');

function youtube_video_statistics($video_id) {
    $json = file_get_contents("https://www.googleapis.com/youtube/v3/videos?part=statistics&id=" . $video_id . "&key=". YOUTUBE_DATA_API_KEY );
    $jsonData = json_decode($json);
    $views = $jsonData->items[0]->statistics->viewCount;
    return $views;
}

//Replace YOUTUBE_VIDEO_ID with your actual YouTube video Id
echo youtube_video_statistics('YOUTUBE_VIDEO_ID');

I am using this solution in my application and it is working as of today. So get the API Key and YouTube video ID and replace them in the above code (Second Line and Last Line) and you should be good to go.


This probably is not what you want but you could scrap the page for the information using the following:

document.getElementsByClassName('watch-view-count')[0].innerHTML

You can use JQuery, don't forget to replace Your-Api-Key string from the code below, follow the link to find your own Api key google developers console

<script>
    $.getJSON('https://www.googleapis.com/youtube/v3/videospart=statistics&id=Qq7mpb-hCBY&key=Your-Api-Key', function(data) {
        console.log("viewCount: ", data.items[ 0 ].statistics.viewCount);
    });
</script>

Here an example that I used in my TubeCount app.

I also use the fields parameter to filter the JSON result, so only the fields that I need are returned.

var fields = "fields=openSearch:totalResults,entry(title,media:group(yt:videoid),media:group(yt:duration),media:group(media:description),media:group(media:thumbnail[@yt:name='default'](@url)),yt:statistics,yt:rating,published,gd:comments(gd:feedLink(@countHint)))";

var channel = "wiibart";

$.ajax({
    url: "http://gdata.youtube.com/feeds/api/users/"+channel+"/uploads?"+fields+"&v=2&alt=json",
    success: function(data){

        var len = data.feed.entry.length;

        for(var k =0; k<len; k++){
            var yt = data.feed.entry[k];
            v.count = Number(yt.yt$statistics != undefined && yt.yt$statistics.viewCount != undefined ? yt.yt$statistics.viewCount : 0);
        }
    }
});

You can use the new YouTube Data API v3

if you retrieve the video, the statistics part contains the viewCount:

from the doc:

https://developers.google.com/youtube/v3/docs/videos#resource

statistics.viewCount / The number of times the video has been viewed.

You can retrieve this info in the client side, or in the server side using some of the client libraries:

https://developers.google.com/youtube/v3/libraries

And you can test the API call from the doc:

https://developers.google.com/youtube/v3/docs/videos/list

Sample:

Request:

GET https://www.googleapis.com/youtube/v3/videos?part=statistics&id=Q5mHPo2yDG8&key={YOUR_API_KEY}

Authorization:  Bearer ya29.AHES6ZSCT9BmIXJmjHlRlKMmVCU22UQzBPRuxzD7Zg_09hsG
X-JavaScript-User-Agent:  Google APIs Explorer

Response:

200 OK

- Show headers -

{
 "kind": "youtube#videoListResponse",
 "etag": "\"g-RLCMLrfPIk8n3AxYYPPliWWoo/dZ8K81pnD1mOCFyHQkjZNynHpYo\"",
 "pageInfo": {
  "totalResults": 1,
  "resultsPerPage": 1
 },
 "items": [
  {

   "id": "Q5mHPo2yDG8",
   "kind": "youtube#video",
   "etag": "\"g-RLCMLrfPIk8n3AxYYPPliWWoo/4NA7C24hM5mprqQ3sBwI5Lo9vZE\"",
   "statistics": {
    "viewCount": "36575966",
    "likeCount": "127569",
    "dislikeCount": "5715",
    "favoriteCount": "0",
    "commentCount": "20317"
   }
  }
 ]
}

PHP JSON

$jsonURL = file_get_contents("https://www.googleapis.com/youtube/v3/videos?id=$Videoid&key={YOUR-API-KEY}&part=statistics");
$json = json_decode($jsonURL);

First go through this one by uncommenting

//var_dump(json);

and get views count as:

$vcounts = $json->{'items'}[0]->{'statistics'}->{'viewCount'};

Version 2 of the API has been deprecated since March 2014, which some of these other answers are using.

Here is a very simple code snippet to get the views count from a video, using JQuery in the YouTube API v3.

You will need to create an API key via Google Developer Console first.

<script>
  $.getJSON('https://www.googleapis.com/youtube/v3/videos?part=statistics&id=Qq7mpb-hCBY&key={{YOUR-KEY}}', function(data) {
    alert("viewCount: " + data.items[0].statistics.viewCount);
  });
</script>

Using youtube-dl and jq:

views() {
    id=$1
    youtube-dl -j https://www.youtube.com/watch?v=$id |
        jq -r '.["view_count"]'
}

views fOX1EyHkQwc