33 – YouTube Data API – Get All PlaylistItems For A Playlist

In continuation of article 32 previous to this, we see how to fetch the playlistItems in a playlist. As per the API a playlistItem can contain different kinds of data, but so far, it only comprises of video elements. Which means that each playlistItem will have the same fields as a video viz.title, description, publishedAt, videoId etc.

The logic to get playlistItems is the same as getting videos from a channel. Each request can get a maximum of 50 items. There is no option to sort the items on any field. And in case there are more playlists available, the nextPageToken will contain the token to do the next fetch request.

The Request URL is

GET https://www.googleapis.com/youtube/v3/playListItems

Sample code to fetch the playlistItems of a PlayList.

<?php
    error_reporting(E_ALL ^ E_NOTICE ^ E_WARNING ^ E_DEPRECATED);
    set_time_limit(60 * 3);
    
    $g_youtubeDataAPIKey = "xxx";
        
    $output = ""; 
    $channelId = "UC5_j0dmvXE0xs6ra-clGz4A";
    $playlistId = "PLC98ABC853EAEFD7F";

        // make api request
        $url = "https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&playlistId=" .
            $playlistId. "&maxResults=50&key=" . $g_youtubeDataAPIKey;
	echo($url . "\n");
	//$handle = fopen('php://temp', 'w+');

        $curl = curl_init();
        curl_setopt_array($curl, array(
                    CURLOPT_RETURNTRANSFER => 1,
                    CURLOPT_URL => $url,
                    CURLOPT_USERAGENT => 'Codular Sample cURL Request',
                    CURLOPT_SSL_VERIFYPEER => 1,
                    CURLOPT_SSL_VERIFYHOST=> 0,
		    CURLOPT_VERBOSE=>false,
		    CURLOPT_FOLLOWLOCATION => TRUE
                    ));
        $resp = curl_exec($curl);

        curl_close($curl);
    if ($resp) {
            $json = json_decode($resp);
            if ($json) {
                $nextPageToken = $json->nextPageToken;
                $total = $json->pageInfo->totalResults;
                $items = $json->items;
            }

            echo("nextpage=" . $nextPageToken . "<br>total=" . $total . "<br>items=" . count($items));
            foreach($items as $item) {
                $videoId = $item->snippet->resourceId->videoId;
                $videoTitle = $item->snippet->title;
                $videoDesc = $item->snippet->description;
                $thumbnail= $item->snippet->thumbnails->high->url;
                $rawDate = $item->snippet->publishedAt;

                $output .= $videoId . ", " . $videoTitle . "," . $rawDate . "\n";
                    
            }

            // second level search using nextpage token
            echo("<br><h2>Second phase</h2><br>");
            while ($nextPageToken != null) {
                $url = "https://www.googleapis.com/youtube/v3/search?part=snippet&channelId=" .
                    $channelId. "&maxResults=50&order=date&type=video&" .
                    "&pageToken=" . $nextPageToken . "&key=" . $g_youtubeDataAPIKey;
                
                $curl = curl_init();
                curl_setopt_array($curl, array(
                            CURLOPT_RETURNTRANSFER => 1,
                            CURLOPT_URL => $url,
                            CURLOPT_USERAGENT => 'Codular Sample cURL Request',
                            CURLOPT_SSL_VERIFYPEER => 1,
                            CURLOPT_SSL_VERIFYHOST=> 0,
                            CURLOPT_FOLLOWLOCATION => TRUE
                            ));
                $resp = curl_exec($curl);

                if ($resp) {
                    $json = json_decode($resp);
                    if ($json) {
                        $nextPageToken = $json->nextPageToken;
                        $total = $json->pageInfo->totalResults;

                        $items = $json->items;
                    }

                    echo("nextpage=" . $nextPageToken . "<br>total=" . $total .
                            "<br>items=" . count($items));
            
                    foreach($items as $item) {
		        $videoId = $item->snippet->resourceId->videoId;
                        $videoTitle = $item->snippet->title;
                        $videoDesc = $item->snippet->description;
                        $thumbnail= $item->snippet->thumbnails->high->url;
                        $rawDate = $item->snippet->publishedAt;
                        
		 	$output .= $videoId . ", " . $videoTitle . "," . $rawDate . "\n";


                    } // foreach
                    
                } // if $resp
                
                // sometimes pagetoken is filled but no items are fetched , in such a case stop the code
                if (count($items) == 0)
                    $nextPageToken = null;
                    
            } // while $nextPageToken

	    echo($output);
           	   	 
    } // if $resp || incremental
    else {
	exit("Youtube api request did not work");
    }

    
?>

It is assumed that the code will be run on the command so the output uses newline and tab symbols for basic formatting. You can use html tags if the code will be run in a browser. Here is some part of the output:

https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&playlistId=PLC98ABC853EAEFD7F&maxResults=50&key=AIzaSyAJrlFVIJEP0ZgT9tMCJZp_ILy6MsjGhTA
nextpage=<br>total=25<br>items=25<br><h2>Second phase</h2><br>C1ttJju1RKc, Corso Pascal (Turbo/FPC)  - 01 Struttura del corso,2011-12-31T07:55:09Z
cblRxEP9wo0, Corso Pascal (Turbo/FPC)  02 Struttura. Identificatori. Principali errori.,2011-12-31T07:55:09Z
wgXtF-R1trU, Corso Pascal (Turbo/FPC) 03 Unit. Crt. Uso dell'Help. Colori. Costanti. Un esercizio.,2011-12-31T14:44:54Z
PGRj2Cp4Uz4, Corso Pascal (Turbo/FPC) 04 Ciclo FOR. Assegnamenti. Debugger.,2011-12-31T19:52:34Z
bpOwOS6-2v4, Corso Pascal (Turbo/FPC)  05 Cicli annidati. Input da tastiera. Numeri casuali. Delay.,2012-01-01T16:35:50Z
kA672A0dwKo, Corso Pascal (Turbo/FPC) 06 Ciclo Repeat. Contatori. If ... then. Break point condizionali.,2012-01-01T20:44:27Z
rEq7FDuvhTw, Corso Pascal (Turbo/FPC) 07 Condizioni and/or, for vs repeat,2012-01-01T20:44:01Z
7G9Wm8ZZk60, Corso Pascal (Turbo/FPC)  08 cicli annidati, if in cascata, numeri casuali, while,2012-01-01T21:27:17Z
LJdHv-BRaLI, Corso Pascal (Turbo/FPC) 09 Gioco dei dadi, case of,2012-01-01T22:22:17Z
SCxJPsgPxFo, Corso Pascal (Turbo/FPC) 10  Esercizi e dispensa,2012-01-02T19:33:09Z
ZU95iarF1EE, Corso Pascal (Turbo/FPC) 11 Complessità del sw, top down, sottoprogrammi,2012-01-03T16:33:51Z
JkkGblGkQu0, Corso Pascal (Turbo/FPC) 12 Procedure e funzioni,2012-01-04T23:51:07Z
k3lvR2DwDsU, Corso Pascal (Turbo/FPC) 13 Array, algoritmi classici con gli array,2012-01-05T21:07:49Z
NiZjoutMgVw, Corso Pascal (Turbo/FPC) 14 Array bidimensionali (matrici) ed algoritmi classici,2012-01-06T22:25:39Z
fz_VIyowkVo, Corso Pascal - 15 (Turbo/FPC) Record,2012-01-08T19:28:01Z
MN8CDG4B0_w, Corso Pascal 16 (Turbo/FPC) File di testo,2012-01-11T16:49:51Z
B1puG7xgyK4, Corso Pascal 17 (Turbo/FPC) File Tipizzati,2012-01-11T18:45:33Z
YiQo0JcUIQM, Corso Pascal 18 (Turbo/FPC) Puntatori, RAM dinamica,2012-01-12T22:22:42Z
OzuJSQMrFew, Corso Pascal 19 (Turbo/FPC) Ricorsione,2012-01-14T22:38:03Z
R40FaRUBxks, Corso Pascal 20 (Turbo/FPC) Alberi binari con puntatori,2012-01-15T09:56:14Z
asd6O3NQ_mI, Corso Pascal 21 (Turbo/FPC) Torre di Hanoi in dettaglio (ricorsione),2012-01-15T10:25:33Z
PuRFjD2h5Wk, Corso Pascal 22 (Turbo/FPC) Grafica,2012-01-18T16:06:56Z
PyQwGhqidm0, Video Corso Pascal - 23 (Turbo e FPC),2012-01-19T21:00:27Z
lBB3Y0NXxkA, Corso Pascal 25 (Turbo/FPC) Usare l'editor 'al massimo',2012-01-22T12:08:09Z
ulL__tpzAKk, Corso Pascal - Ed ora??,2012-01-24T19:14:31Z

Be the first to comment

Leave a Reply

Your email address will not be published.


*