Creating a simple API for the TV Show Tracker app

I've wanted to create a simple API for my TV Show Tracker app for some time now and I've finally got round to creating it; you can see the fruits of my labour at the bottom of the page where it's pulling in all the episodes that I've recently watched.

There's 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've got an episodes method which proccesses 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:

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
			 * Last Watched
			 * @param int limit 
			case 'last_watched':
                            // get episodes
        echo json_encode($json);

For authentication I've created an API key for each user, this is a salted hash and is unique to that User so we know we're 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's using it and if it's being abused.

Using the API

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

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, "");
		curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_TIMEOUT, 10);
		$output = curl_exec($ch);

		echo $output;

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

The Javascript code

(function ($) {
		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="" target="_blank">TV Show Tracker</a>)</span></h3><div id="tv_show_tracker" class="row">';
				// loop through episodes
					// 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="''" target="_blank">';
					    html += '<img src="'+v.Show.poster.small+'" alt="'' 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

Wrapping Up

Getting this up and running wasn't too difficult and I can now display the Shows I'm currently watching at the bottom of the page. I need to beef up the API and create more features so hopefully I'll have time in the near future to do this, I'll also probably do the same for my Film Tracker app so that I can display the films I've recently seen. Any issues or questions get in touch

Posted on 22nd June 2012
4 years, 8 months, 6 days ago

comments powered by Disqus