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



I think, the easiest way, is to get video info in JSON format. If you want to use JavaScript, try jQuery.getJSON()... But I prefer PHP:

$video_ID = 'your-video-ID';
$JSON = file_get_contents("{$video_ID}?v=2&alt=json");
$JSON_Data = json_decode($JSON);
$views = $JSON_Data->{'entry'}->{'yt$statistics'}->{'viewCount'};
echo $views;

Ref: Youtube API - Retrieving information about a single video


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.

  $.getJSON('{{YOUR-KEY}}', function(data) {
    alert("viewCount: " + data.items[0].statistics.viewCount);

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 = '' + videoId + '?v=2&alt=json',
   embedUrl = '//' + 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 =$statistics.viewCount;

//Embed Video

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

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

curl | 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.


Use the Google PHP API 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:

class YouTubeVideo
    // video id
    public $id;

    // generate at
    private $apiKey = 'REPLACE_ME';

    // google youtube service
    private $youtube;

    public function __construct($id)
        $client = new Google_Client();

        $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()
            // 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>',
        } catch (Google_Exception $e) {
            return sprintf('<p>An client error occurred: <code>%s</code></p>',

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


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";

    url: ""+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($statistics != undefined &&$statistics.viewCount != undefined ?$statistics.viewCount : 0);


$jsonURL = file_get_contents("$Videoid&key={YOUR-API-KEY}&part=statistics");
$json = json_decode($jsonURL);

First go through this one by uncommenting


and get views count as:

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

Using youtube-dl and jq:

views() {
    youtube-dl -j$id |
        jq -r '.["view_count"]'

views fOX1EyHkQwc

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


You can use the new YouTube Data API v3

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

from the doc:

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:

And you can test the API call from the doc:




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


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"

You can use this too:

    $youtube_view_count = json_decode(file_get_contents(''))->entry->{'yt$statistics'}->viewCount;
    echo $youtube_view_count;

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    

function youtube_video_statistics($video_id) {
    $json = file_get_contents("" . $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.


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

    $.getJSON('', function(data) {
        console.log("viewCount: ", data.items[ 0 ].statistics.viewCount);


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.