June 15, 2014

June 15, 2014
In this article, we are going to discuss about How to create an API for TV Show tracker app in cakephp. There is 2 parts to the API, one is the server part on my app and the other is the client which requests information and displays it. As the TV Show Tracker app is built using CakePHP I created an ApiController which deals with all the requests for information.

I have got an episodes method, which processes all the requests for episode information, currently the only action available is last_watched which gets the recently watched episodes for that user.

Below is some sample code so that you know what I'm talking about

<?php
class ApiController extends AppController {
        /**
* Get Episode information
* $params[0] = api key
* $params[1] = action (last_watched)
* $params[2] = options (last_watched = limit)
*/
function episodes() {
// get params
$params = $this->params['pass'];
// switch based on action
switch($params[1])
{
/**
* Last Watched
* @param int limit 
*/
case 'last_watched':
                            // get episodes
break;
}
        echo json_encode($json);
        }
}

For authentication I have created an API key for each user, this is a salted hash and is unique to that User so we know we are only going to return their information. This was easier than I thought and works quite well. All calls are logged so that I know who is using it and if it is being abused.

Using the API

To use the API you will need to query the following URL:

http://www.tvshowtracker.co.uk/api/episodes/API_KEY/last_watched

This will bring back a JSON encoded string with all the Episode & Show information which can then be used in you application. I'm using it on the blog by sending a ajax request to one of my Controller actions, this is then using cURL to request the API URL and bring back any results. This is then passed back to the Javascript file where I loop through the Episodes and display the Show Posters and info.

The PHP code

/**
 * Ajax call to TV Show Tracker
 */
public function ajax_tv_show_tracker() {
if(!$this->request->is('ajax')) {
throw new NotFoundException('Action not allowed');
}

if (function_exists('curl_init')) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.tvshowtracker.co.uk/api/episodes/API_KEY/last_watched/8");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
$output = curl_exec($ch);
curl_close($ch);

echo $output;
exit;
}

echo json_encode(array('success'=>FALSE));
exit;
}

The Javascript code

(function ($) {

$.ajax({
type: "GET",
url: "/posts/ajax_tv_show_tracker",
dataType: "json",
success: function(episodes){
// call was successful
if(episodes.success) {
// build up HTML
var html = '<h3>Recently Watched Shows <span style="font-size:14px;">(tracked with <a href="http://www.tvshowtracker.co.uk" target="_blank">TV Show Tracker</a>)</span></h3><div id="tv_show_tracker" class="row">';

// loop through episodes
$(episodes.episodes).each(function(k,v){
// deal with first & last in row
var class_name = '';
if(k==0) {
class_name = ' alpha';
} else if(episodes.episodes.length==8 && k==3) {
class_name = ' omega';
} else if(k==7) {
class_name = ' omega';
}

// build up episode image & link
html += '<div class="two columns show'+class_name+'">';
 html += '<a href="'+v.Show.link+'" target="_blank">';
   html += '<img src="'+v.Show.poster.small+'" alt="'+v.Show.name+' Poster" style="width:100%; display:block;"/>';
 html += '</a>';
 html += '<small>Episode '+v.Episode.season_number+'x'+v.Episode.episode_number+'</small>';
html += '</div>';
});

html += '</div>';

// inject into page
$('.site_images').after(html);
}
}
});

})(jQuery);

0 comments:

Post a Comment