Retrieve YouTube playlist videos using YouTube API

Planning to integrate YouTube videos to your application? This post is for you. I will show how to retrieve YouTube videos from YouTube playlist using YouTube API.

In order to use YouTube API, you need to create or obtain API Key. By using this key, you can make YouTube Data API requests. I will be using PHP to fetch videos and display in the webpage.

1.  Create YouTube API Key

To create YouTube API key, login to Google Developers Console using your Google Account and then create a project. This will show the list of libraries available. From the list, make sure to select YouTube Data API and enable it. Then it will show the screen similar to the following image:

YouTube API Credential
Creating Credential to use YouTube API

Now that we have enabled the YouTube Data API v3, we need to Create credentials to use this API. Click the Create Credentials button to create credential. This will open form to add credentials. After filling the form properly, you will get the YouTube API Key to access data.

Add credentials from screenshot
Add credentials to your project

Click What credentials do I need? button to get API. It will create API and show the screen similar as the following:

YouTube API Credentials Screen
Get YouTube API Credentials

Note down this API key and lets start fetching YouTube data.

2. Retrieve YouTube playlist videos

To retrieve YouTube Playlist videos, we need API key as well as YouTube Playlist ID. We can find YouTube Playlist Id simply by clicking the Playlist link in YouTube. The URL of that page contains Playlist Id. The following PHP code makes API request to fetch playlist videos from YouTube. Data fetched from YouTube is in JSON format.

<?php

$api_key = 'your-api-key';

$playlist_id =  'playlist_id'; 

$api_url = 'https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=25&playlistId='. $playlist_id . '&key=' . $api_key;
      
$playlist = json_decode(file_get_contents($api_url));

?>

3. Listing Videos

We can list videos fetched from above code in our webpage. Here’s a sample implementation.

<ul>
<?php foreach($playlist->items AS $item): ?>
  <li><img src="<?php echo $item->snippet->thumbnails->default->url; ?>"> <h4><?php echo $item->snippet->title;  ?></h4></li>
<?php endforeach; ?>
</ul>

In this way, we can integrate YouTube playlist to our webpage using YouTube API v3. There are lot of features that can be integrated by using YouTube Data API.

We can also fetch information about videos as well as search YouTube videos using YouTube API.

Furthermore, we can use the API to upload videos, manage playlists and subscriptions, update channel settings, and much more. Google Developer page for YouTube is nice resource to further explore these features.

6 Comments

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.