Wern Ancheta

Adventures in Web Development.

Working With Youtube Data API in PHP

| Comments

Decades ago I got this project where I needed to work with the Youtube API to get the details of videos uploaded by a specific channel. And then create something like a mini-youtube website out of it. Just kidding about the decades part, it was probably 4-6 months ago. Anyway its only this time that I got the time to actually write about it. So here it goes.

Getting API Credentials

First you need to get the API credentials from your Google Console. There’s only a single API credential for all of the APIs that Google offers. So you might already have one. If you do then all you have to do is enable the API in your Google Console page. Currently you would see something like this when you go to APIs & Auth and then click on APIs on your Google Console:

google apis

What we need is the Youtube Data API v3. Click that and enable it. If you do not have an API credential then you can click on ‘Credentials’ under the APIs & Auth and click on ‘Create new Key’ under the Public API Access section. Choose Server Key as the key type since were working primarily on the server. Don’t take my word for it though. Based on my experience sometimes this doesn’t work and you actually need to select Browser Key. I just hope google has fixed this already. Server keys are only supposed to be used in the server and browser keys on the client side. Clicking on either browser key or server key will generate an API Key for you. This is the key that you will use when you need to talk to the Youtube API.

Dependencies

As we are primarily going to be requesting data from another server, we will need curl. If you don’t have it yet, install it on your system. Here’s how you install it on Ubuntu:

1
2
3
sudo apt-get install curl
sudo apt-get update
sudo apt-get install libcurl3 php5-curl

If you’re using another Operating System then feel free to ask Google.

Playing with the API

To make things easier we need a library that will do most of the heavy-lifting for us. Things like signing the request, constructing it and actually making the request to the server. Because were lazy folks we don’t need to do that every time we need to talk to an API. Thankfully an awesome guy in the alias of madcoda has already done that work for us. If you already have composer installed, simply execute the following command inside your project directory:

1
composer require madcoda/php-youtube-api

This will install the library into your vendor directory, autoload it and add it to your composer.json file.

Once its done you can now use the library by including the autoload.php file under the vendor directory and then use the Madcoda\Youtube namespace.

1
2
3
4
5
<?php
require 'vendor/autoload.php';

use Madcoda\Youtube;
?>

Next create a new instance of the Youtube class and pass in the API Key that you acquired earlier as the key item in an array.

1
2
3
<?php
$youtube = new Youtube(array('key' => 'YOUR_API_KEY'));
?>

Searching

With this library you can search for videos, playlists and channels by using the search method. This method takes up your query as its argument. For example you want to find ‘Awesome’:

1
2
3
<?php
$results = $youtube->search('Awesome');
?>

This will return something similar to the following if you use print_r on the $results:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
Array
(
[0] => stdClass Object
    (
        [kind] => youtube#searchResult
        [etag] => "tbWC5XrSXxe1WOAx6MK9z4hHSU8/xBkrpubrM2M6Xi88aNBfaVJV6gE"
        [id] => stdClass Object
            (
                [kind] => youtube#video
                [videoId] => qmTDT92VIRc
            )

        [snippet] => stdClass Object
            (
                [publishedAt] => 2015-01-23T23:03:31.000Z
                [channelId] => UCZpKcVBccIjO9n0RXx3ZGFg
                [title] => PEOPLE ARE AWESOME 2015 (UNBELIEVABLE)
                [description] => People are Awesome 2015 unbelievable talent and natural skills! Subscribe to NcCrullex for more people are awesome videos. Chris Samba Art Channel: ...
                [thumbnails] => stdClass Object
                    (
                        [default] => stdClass Object
                            (
                                [url] => https://i.ytimg.com/vi/qmTDT92VIRc/default.jpg
                            )

                        [medium] => stdClass Object
                            (
                                [url] => https://i.ytimg.com/vi/qmTDT92VIRc/mqdefault.jpg
                            )

                        [high] => stdClass Object
                            (
                                [url] => https://i.ytimg.com/vi/qmTDT92VIRc/hqdefault.jpg
                            )

                    )

                [channelTitle] => NcCrulleX
                [liveBroadcastContent] => none
            )

    )

As you can see most of the data that you might want is stored in the snippet item. Things like the title, description and URL to the thumbnails.

You might ask, how you would know if the item is a video, playlist or channel? You might have already noticed based on the results above. Its located under the id –> kind. It would have a kind of youtube#video if its a video. youtube#channel if its a channel and youtube#playlist if its a playlist. Don’t believe me? Try using the API to search for ‘the new boston’ and you’ll see.

If you only want to search for videos then you can use the searchVideos method. Just like the search method this takes up your query as its argument:

1
2
3
<?php
$results = $youtube->searchVideos('Ninja');
?>

If you only want to get videos from a specific channel, you can do it in 2 calls. First you need to get the channel id by using the getChannelByName method and then extract the id from the result that you get and then use the id for the searchChannelVideos to search for videos in a specific channel:

1
2
3
4
<?php
$channel = $youtube->getChannelByName('thenewboston');
$results = $youtube->searchChannelVideos('ruby', $channel->id);
?>

The code above would return the first page of results for the ‘ruby’ videos in ‘thenewboston’ channel.

If you only want to return playlists on a specific channel, you can do:

1
2
3
4
<?php
$channel = $youtube->getChannelByName('thenewboston');
$results = $youtube->getPlaylistsByChannelId($channel->id);
?>

If you want to get the items in a playlist, you can do it in 3 calls:

1
2
3
4
5
<?php
$channel = $youtube->getChannelByName('thenewboston');
$playlists = $youtube->getPlaylistsByChannelId($channel->id);
$playlist_items = $youtube->getPlaylistItemsByPlaylistId($playlists[0]->id);
?>

If you want to be more liberal with your search, you can use the searchAdvanced method:

1
2
3
4
5
6
7
<?php
$results = $youtube->searchAdvanced(array(
    'q' => 'fruits',
    'part' => 'snippet',
    'order' => 'rating'
));
?>

Here’s a breakdown of the parameters we’ve just used:

  • q – your query
  • part – the part of the result which you want to get. Earlier in the sample result we saw that there are only 2 parts. id and snippet. This parameter allows you to specify that. If you only need the video, playlist or channel id then supply id as the part. If you need the full details then use snippet. If you need both then you can use a comma-separated list: id, snippet.
  • order – the basis of the ordering. In the example we used rating. This orders the results based on the highest ratings to the lowest. Not really sure what the ratings is. But the first thing that comes to mind is the number of likes in the video. You can also use viewCount if you want. This will order the results with the videos, playlists or channels which has the highest number of views to the lowest.
  • type – the type of item. This can either be video, playlist, or channel.

There’s a whole bunch more which you can specify as a parameter. Be sure to check out the search reference.

Pagination

You can also paginate results. First you need to make an initial request so you can get the nextPageToken. Then check if the page token exists, if it does then add a pageToken item to the parameters that you supplied earlier. And then make another request. Since we supplied the nextPageToken, this will now navigate to the second page of the same result set. By default the youtube data api only returns 10 rows per request. This means that the second page will show you row 11 up to 21.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<?php
$params = array(
    'q' => 'Ruby',
    'type' => 'video',
    'part' => 'id, snippet',
    'maxResults' => 100
);

$search = $youtube->searchAdvanced($params, true);

//check for a page token
if(isset($search['info']['nextPageToken'])){
    $params['pageToken'] = $search['info']['nextPageToken'];
}

//make another request with the page token added
$search = $youtube->searchAdvanced($params, true);

//do something with the search results her
?>         

You can also use the paginateResults method to implement pagination. Just like the method above, we need to make an initial request to get the nextPageToken. We then store it to an array so we can navigate through the results easily. The paginateResults method takes up the original search parameters as its first argument and the page token as its second. So all you have to do is supply the nextPageToken that you got from the previous results as the second argument for the paginateResults method to navigate to the next page. Note that in the example below, the indexes for the $page_tokens are just hard-coded. You will have to implement the generation of pagination links yourself and then use their index when navigating through the results. Also note that the results aren’t cached, this means that whenever you paginate through the results a new request is made to the youtube data api. You will also need to implement caching if you don’t want to easily run out of requests you can make.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<?php
//your search parameters
$params = array(
    'q' => 'Python',
    'type' => 'video',
    'part' => 'id, snippet',
    'maxResults' => 100
);

//array for storing page tokens
$page_tokens = array();

//make initial request
$search = $youtube->paginateResults($params, null);

//store page token
$page_tokens[] = $search['info']['nextPageToken'];

//navigate to the next page
$search = $youtube->paginateResults($params, $page_tokens[0]);

//store page token token
$page_tokens[] = $search['info']['nextPageToken'];

//navigate to the next page
$search = $youtube->paginateResults($params, $page_tokens[1]);

//store page token
$page_tokens[] = $search['info']['nextPageToken'];

//navigate to the previous page
$search = $youtube->paginateResults($params, $page_tokens[0]);

//do something with the search results here
?>

Conclusion

That’s it! In this tutorial you’ve learned how to work with the Youtube Data API in PHP. You’ve learned how to get the info of a specific video, get general details about videos in a specific channel, get the videos in a specific playlist, and also search for videos, playlists and channels using a query. Don’t forget to work through the API request limits though. The limit information can be found on the Youtube Data API page on your Google Console.

Resources

Comments