YouTube

A YouTube API Library for the CodeIgniter PHP Framework

Jim Saunders
August 2011

Introduction

In this tutorial, we will be covering how to set up and use the YouTube API libraries developed for the CodeIgniter PHP framework. Prior to the development of these libraries, the only way to contact and use the YouTube API involved importing a large portion of the Zend framework, thereby considerably increasing project file size.

It is worth mentioning that although these library files were developed for CodeIgniter, very little of the framework is used and with a small amount of effort the files can be converted to work in any PHP project. However, that is outside the scope of this tutorial.

This tutorial expects that you have a good understanding of OAuth and CodeIgniter.

The Files

The files for this project can be found on GitHub at: https://github.com/jimdoescode/CodeIgniter-YouTube-API-Library

google_oauth.php

This file should be placed in ./application/libraries. This library retrieves an OAuth access token to authenticate with YouTube. Note: You can use this library to get an OAuth token for any Google service by setting the appropriate scope parameter. Further documentation can be found here.

youtube.php

This file should be placed in ./application/libraries. This library interacts with the API to submit your requests and retrieve XML responses to those requests. Further documentation can be found here.

oauth_helper.php

This file should be placed in ./application/helpers. It signs and builds OAuth HTTP headers and is used internally by both library files. Further documentation can be found here.

Prep Work

Before loading the library files, you must perform two tasks:

  1. Get an API key to access YouTube's API. To obtain a key, go to http://code.google.com/apis/youtube/dashboard/gwt/index.html and provide the necessary information about your application. I recommend placing the key in a config file for easy access.
  2. Establish OAuth Authentication from your new domain. You can do this by visiting https://www.google.com/accounts/ManageDomains and following the instructions to register a new domain with Google. Once you have registered a new domain, click the link to "Manage" your new domain. From that point, you have two options to determine which OAuth signing algorithm to use.
    1. To use HMAC-SHA1 signing for OAuth authentication, copy the OAuth Consumer Key and OAuth Consumer Secret (available on the "Manage" page for your new domain) into a config file that your application can reference.
    2. Follow these instructions to use RSA-SHA1 signing for OAuth authentication:
      1. Generate a X.509 cert by following the instructions provided here.
      2. Upload the generated file upload to Google.
      3. Copy the OAuth Consumer Key.
      4. Place the X.509 cert file into your project. (Note: Make sure you restrict access to this file from the web.)
      5. Place the Consumer Key and the relative path to your cert file into a config file so they may be referenced later.

Let's Get Down to Business

Now that you have downloaded the files, placed them in the correct locations, and completed the prep work, you should be able to start contacting the API servers. You can look at the example controller provided in the repository.

The example below shows how to initialize the library without OAuth authentication. (The API key is stored in a config file.)

$params['apikey'] = $this->config->item('youtube_api_key');
$this->load->library('youtube', $params);

Here are some methods in the YouTube library that do not require user authentication:

$this->youtube->getVideoEntry($videoId);
$this->youtube->getRelatedVideoFeed($videoId, $start = 1, $count = 10);
$this->youtube->getVideoResponseFeed($videoId, $start = 1, $count = 10);
$this->youtube->getKeywordVideoFeed(array $keywords, $start = 1, $count = 10);
$this->youtube->getVideoCommentFeed($videoId, $start = 1, $count = 10);
$this->youtube->getTopRatedVideoFeed($start = 1, $count = 10);
$this->youtube->getMostViewedVideoFeed($start = 1, $count = 10);
$this->youtube->getRecentlyFeaturedVideoFeed($start = 1, $count = 10);
$this->youtube->getWatchOnMobileVideoFeed($start = 1, $count = 10);

If you require an authenticated user to access the API, then you must use the google_oauth library to retrieve an OAuth access token. You can do this by creating a new CodeIgniter controller and adding the following methods.

public function youtube_request()
{
    $params['key'] = $this->config->item('google_consumer_key');
    $params['secret'] = $this->config->item('google_consumer_secret');
    $params['algorithm'] = "HMAC-SHA1";

    $this->load->library('google_oauth', $params);
    $response = $this->google_oauth->get_request_token(site_url("welcome/youtube_access"));
    
    $this->_store_somewhere($response['token_secret']); //pseudo code for temporarily storing this value

    redirect($response['redirect']);
}

public function youtube_access()
{
    $params['key'] = $this->config->item('google_consumer_key');
    $params['secret'] = $this->config->item('google_consumer_secret');
    $params['algorithm'] = "HMAC-SHA1";    

    $this->load->library('google_oauth', $params);

    $token_secret = $this->_get_from_storage('token_secret'); //pseudo code for retrieving the stored value

    $oauth = $this->google_oauth->get_access_token(false, $token_secret);

    $this->_store_in_db('youtube_token', $oauth['oauth_token']); //pseudo code for permanently storing this value
    $this->_store_in_db('youtube_secret', $oauth['oauth_token_secret']); //pseudo code for permanently storing this value
        
    redirect(site_url());
} 

At this point, you should have an OAuth access token and a token secret that you can use to authenticate YouTube API requests for a particular user. Now load the youtube library with your API key, your OAuth consumer key, your OAuth consumer secret (a file path if you have a X.509 cert for RSA-SHA1), the signing algorithm (either HMAC-SHA1 or RSA-SHA1). The access token should be an array with the urlencoded token value and, if you are using HMAC-SHA1 signing, the oauth_token_secret should also be urlencoded.

$params['apikey'] = $this->config->item('youtube_api_key');
$params['oauth']['key'] = $this->config->item('google_consumer_key');
$params['oauth']['secret'] = $this->config->item('google_consumer_secret');
$params['oauth']['algorithm'] = $this->config->item('google_signing_algo');
$params['oauth']['access_token'] = array('oauth_token'=>urlencode($token), 'oauth_token_secret'=>urlencode($secret)); 

$this->load->library('youtube', $params);

Now the library can be used to it’s full potential. You can use any of the following methods to make authenticated API requests. Note: The user parameter can be any YouTube user name. The special value 'default' means the authenticated user.

$this->youtube->getPlaylistListFeed($user = 'default', $start = 1, $count = 10);
$this->youtube->getSubscriptionFeed($user = 'default', $start = 1, $count = 10);
$this->youtube->getContactFeed($user = 'default', $start = 1, $count = 10);
$this->youtube->getUserUploads($user = 'default', $start = 1, $count = 10);
$this->youtube->getUserFavorites($user = 'default', $start = 1, $count = 10);
$this->youtube->getUserProfile($user = 'default');
$this->youtube->getUserActivity($user = 'default');
$this->youtube->getInboxFeedForCurrentUser();

Sending Data to YouTube

So far, the methods outlined have all been retrieving data. However, the API also lets you send data to YouTube.

Direct Uploading

This process involves uploading a video stored on your server to YouTube. Note: The metadata field is the API_XML_Request as defined in the YouTube API documentation and the contenttype is the mimetype of the video to upload.

$this->youtube->directUpload($path, $contenttype, $metadata, $user = 'default');

Browser based Uploading

This involves retrieving an upload URL and token as specified by YouTube and creating an HTML for that will post to that URL.

$this->youtube->getFormUploadToken($metadata);

Other methods that send data are:

$this->youtube->addComment($videoId, $comment, $commentId = false);
$this->youtube->addVideoResponse($videoId, $responseId);
$this->youtube->addNumericRating($videoId, $rating);
$this->youtube->addLikeDislike($videoId, $like);

Conclusion

Although this library has a lot of common API functionality, it is by no means a complete YouTube API reference. Please feel free to contribute any methods that you think are missing by forking the project on GitHub. Also be sure to check out the official YouTube API documentation. Look at the code comments in the youtube library for further documentation on the various parameters of each method.

About the Author

Jim Saunders

Jim Saunders has been doing web development for close to 10 years and random programming for even longer. You can follow him on Twitter or check out his blog. You can also see this library in action at http://gamergameon.com

Authentication required

You need to be signed in with Google+ to do that.

Signing you in...

Google Developers needs your permission to do that.