w3resource

YouTube API Tutorial

Objective

This tutorial demonstrates how to use YouTube API v3 to search and watch videos from YouTube. YouTube offers various powerful ways to play around with videos. You can create awesome applications using the API and also can embed videos from YouTube. It has client libraries in various programming languages to do that. In this application, we will use Google API's PHP Client Library.

If you have not used API's or built any application on top of an API, don't worry. We will guide you from scratch off using an API. Working knowledge of HTML, CSS and PHP is although required for understanding this tutorial.

    

Development Process

Authorizing requests

Like other APIs, YouTube API also requires an authorization. Basically, when the user requests some data from the YouTube through the API, it first needs to be checked and validated by the platform whether the request sent conforms to the scope of the API.

Form authorization, you have to go to the Google APIs Console and login. Click on Create Project.

Create new project Google API Console

Scroll through the list of the APIs available there and Click on Off button next to YouTube Data API v3 to activate the API.

activate the API

It takes you to the Term and Service page. Check I agree to these terms and click Accept. Now you will find that the APIs On, i.e. activated now.

API activated

Now, from the navigation on left-hand side, click on API Access. Click on Create an Auth 2.0 Client ID. A Create Client ID window pops up.

Create Client ID

Fill the information in and click Next. Note that Home Page URL must be url of the page used for the application. On the next page select the kind of application you are creating. For this example, it is a web application, and we select so. Also provide your site or host name and click Create Client ID. That takes you to the page with Client ID and Client secret created. In a moment, we will see where we need Client ID.

PHP code for the application(example.php)

Here is the PHP code for the application. Place the API key generated against the first instance of the $DEVELOPER_KEY.

<?php
if ($_GET['q'] && $_GET['maxResults']) {
  // Call set_include_path() as needed to point to your client library.
  require_once ($_SERVER["DOCUMENT_ROOT"].'/API/youtube/google-api-php-client/src/Google_Client.php');
  require_once ($_SERVER["DOCUMENT_ROOT"].'/API/youtube/google-api-php-client/src/contrib/Google_YouTubeService.php');

  /* Set $DEVELOPER_KEY to the "API key" value from the "Access" tab of the
  Google APIs Console <http://code.google.com/apis/console#access>
  Please ensure that you have enabled the YouTube Data API for your project. */
  $DEVELOPER_KEY = 'AIzaSyDOkg-u9jnhP-WnzX5WPJyV1sc5QQrtuyc';

  $client = new Google_Client();
  $client->setDeveloperKey($DEVELOPER_KEY);

  $youtube = new Google_YoutubeService($client);

  try {
    $searchResponse = $youtube->search->listSearch('id,snippet', array(
      'q' => $_GET['q'],
      'maxResults' => $_GET['maxResults'],
    ));

    $videos = '';
    $channels = '';

    foreach ($searchResponse['items'] as $searchResult) {
      switch ($searchResult['id']['kind']) {
        case 'youtube#video':
          $videos .= sprintf('<li>%s (%s)</li>', $searchResult['snippet']['title'],
            $searchResult['id']['videoId']."<a href=http://www.youtube.com/watch?v=".$searchResult['id']['videoId']." target=_blank>   Watch This Video</a>");
          break;
        case 'youtube#channel':
          $channels .= sprintf('<li>%s (%s)</li>', $searchResult['snippet']['title'],
            $searchResult['id']['channelId']);
          break;
       }
    }

   } catch (Google_ServiceException $e) {
    $htmlBody .= sprintf('<p>A service error occurred: <code>%s</code></p>',
      htmlspecialchars($e->getMessage()));
  } catch (Google_Exception $e) {
    $htmlBody .= sprintf('<p>An client error occurred: <code>%s</code></p>',
      htmlspecialchars($e->getMessage()));
  }
}
?>

<!doctype html>
<html>
  <head>
    <title>YouTube Search</title>
<link href="//www.w3resource.com/includes/bootstrap.css" rel="stylesheet">
<style type="text/css">
body{margin-top: 50px; margin-left: 50px}
</style>
  </head>
  <body>
    <form method="GET">
  <div>
    Search Term: <input type="search" id="q" name="q" placeholder="Enter Search Term">
  </div>
  <div>
    Max Results: <input type="number" id="maxResults" name="maxResults" min="1" max="50" step="1" value="25">
  </div>
  <input type="submit" value="Search">
</form>
<h3>Videos</h3>
    <ul><?php echo $videos; ?></ul>
    <h3>Channels</h3>
    <ul><?php echo $channels; ?></ul>
</body>
</html>

We encourage you to download the code and play around with it.

Previous: Google Plus API Tutorial
Next: Google Maps API V 3 - Tutorial



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/API/youtube/tutorial.php