Site icon Treehouse Blog

Coding a Dynamic IMDb Webapp using My Movie API

The online IMDb website is a crucial resource for any type of digital video media. Online web series, TV shows, and movies are all cataloged with credits to the cast and studio help. IMDb is probably the oldest resource for learning about your favorite shows or movies.

In the spirit of building on top of web applications I went to the site looking for an API section. Unfortunately it doesn’t appear that IMDb has an official API – but we do have My Movie API. This is a RESTful web service which pulls data from IMDb based on a unique ID or title. You have access to a number of popular datasets along with various return formats including JSON and XML.

For this tutorial I want to demonstrate how we can build on top of this API to create a small IMDb webapp. You can do so many different things with this program, but I put together a simple example which can provide a template for other web developers. Check out my live demo to get an idea of what we are creating.

Live DemoDownload Source Code

Getting Started

First I have put together a small HTML5 document which contains a link to the most recent copy of jQuery. You can include a copy directly from the Google CDN or download a local script instead. Also I’ve created a stylesheet named styles.css to hold the page formatting.

<!doctype html>
<html lang="en-US">
<head>
  <meta charset="utf-8">
  <meta http-equiv="Content-Type" content="text/html">
  <title>IMDB API Webapp - Treehouse Demo</title>
  <meta name="author" content="Jake Rocheleau">
  <link rel="shortcut icon" href="http://d15dxvojnvxp1x.cloudfront.net/assets/favicon.ico">
  <link rel="icon" href="http://d15dxvojnvxp1x.cloudfront.net/assets/favicon.ico">
  <link rel="stylesheet" type="text/css" media="all" href="styles.css">
  <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>

Now the webapp itself just contains a few links which also hold IDs from the IMDb website. Once a user clicks on a link we need to query the My Movie API to find out which TV show they clicked. Then we can display more information into the body of the page by parsing over the JSON response.

  <div id="w">
    <h1>IMDB Mini-Webapp</h1>
    <!-- logo icon http://arrioch.deviantart.com/art/Blawb-PSD-245341011 -->
    
    <p class="desc">Select a TV show to display some related information.</p>
    
    <nav id="tvnav">
      <ul class="clearfix">
        <li><a href="#" id="tt0367279">Arrested Development</a></li>
        <li><a href="#" id="tt0386676">The Office</a></li>
        <li><a href="#" id="tt0121955">South Park</a></li>
        <li><a href="#" id="tt0098904">Seinfeld</a></li>
        <li><a href="#" id="tt1826940">New Girl</a></li>
      </ul>
    </nav>
    
    <div id="imdbcontents" class="clearfix"></div>
  </div>

The inner div at the bottom using the ID #imdbcontents will contain the dynamic content. All of the new HTML will be contained inside jQuery variables which then gets appended into the document using .html().

Defining Page Styles

Overall there isn’t a whole lot of detailed stuff to understand from the CSS. I am using a tiled repeating background from Subtle Patterns which adds a nice touch onto the page. Notably the TV navigation section and the dynamic content will require the most styling. But a majority of the stylesheet pertains to custom resets along with the inclusion of a custom web font titled The Girl Next Door.

#tvnav {
  display: block;
  margin-bottom: 25px;
}

#tvnav ul { list-style: none; }
#tvnav ul li { margin-right: 4px; display: block; float: left; }

#tvnav ul li a { 
  padding: 3px 6px;
  color: #5e83c6;
  -webkit-border-radius: 3px;
  -moz-border-radius: 3px;
  border-radius: 3px;
  font-size: 1.2em;
  font-weight: bold;
  text-decoration: none;
  background: #dbe4f3;
}
#tvnav ul li a:hover {
  background: #cbd8f0;
  color: #526890;
}

#imdbcontents { display: block; width: 100%; }

.floatright {
  display: block;
  float: right;
  margin-left: 10px;
  margin-bottom: 5px;
}

All of the navigation links are given rounded borders and background colors to appear more like buttons than regular links. Also the internal content is formatted into a div which starts out completely empty. This means it has an auto-adjusted width that we have to fix using width: 100%;

/* clearfix */
.clearfix:after { content: "."; display: block; clear: both; visibility: hidden; line-height: 0; height: 0; }
.clearfix { display: inline-block; }
 
html[xmlns] .clearfix { display: block; }
* html .clearfix { height: 1%; }

I’ve also applied a small clearfix onto the container of imdbcontents. Using the .floatright class makes positioning the poster artwork so much easier. Clearfix helps to make sure the div will fill out a complete 100% height even if the content itself is shorter than the image. The idea is somewhat dated but still works perfectly. If you want to learn more about clearfix CSS try reading this article to get a better understanding.

jQuery API Access

Now we can dig into the more detailed code for pulling out data from the API and then appending it into HTML. At the bottom of my index file I have opened a new script tag just before the closing </body> tag. We are listening for a click event handler on any of the tv show links which will trigger our API codes.

$(function(){
  
  $('#tvnav ul li a').on('click', function(e){
    e.preventDefault();
    var imdbid  = $(this).attr('id');
    var resturl = "http://mymovieapi.com/?type=json&id="+imdbid+"&release=full&plot=full";
    
    $('#imdbcontents').html('<center><img src="images/loading.gif" alt="loading..."></center>');

All of this code is executed before the Ajax API call. Whenever a user clicks one of these links we first need to call e.preventDefault() against the click event. This way we do not get the hash symbol(#) appended onto the document URL which can also cause the page to jump. You’ll notice from the variable resturl that defining our endpoint is fairly straightforward.

There is a full list on the My Movie API site of alternative parameters you may pass into the request URL. These options are somewhat different depending if you are requesting an IMDb title or ID. Also the final line of code here will append a small loading gif image into the contents container while we await the JSON response.

    $.ajax({
      url: resturl,
      dataType: 'json',
      success: function(data){
        var title  = data.title;
        var genre  = data.genres[0];
        var poster = data.poster.imdb;
        var url    = data.imdb_url;
        var plot   = data.plot;
        var rlseyr = data.year;
        
        var cdiv = $('#imdbcontents');
        
        var thehtml = "<img src=\""+poster+"\" class=\"floatright\">";
        thehtml = thehtml + "<h2>"+title+"</h2>";
        thehtml = thehtml + "<p class=\"genre\">"+genre+" - first aired in "+rlseyr+"</p>";
        thehtml = thehtml + "<p>"+plot+"</p>";
        thehtml = thehtml + "<p><a href=\""+url+"\" target=\"_blank\">View on IMDB →</p>";
        
        cdiv.html(thehtml);
      }
    });

This Ajax request is the most important section and it closes off the whole click event handler. We make an open request to the URL defined with a JSON data type. The new function(data) call actually pulls out the request data upon success, so that we can work with the new JSON contents. Data elements may be accessed using dot notation like data.title. If you want to see a full output of the JSON content simply run console.log(data); and then check your JS console.

After the variables have been defined I start creating a string named thehtml. This is concatenated from one string to the next so we ultimately end up with a single string containing all the HTML data. You will notice this gets passed into the #imdbcontents div which then finally closes the callback function. All of this code is very malleable, and so it’s easy to manipulate the position of content or even include other bits of data from the JSON response.

Live DemoDownload Source Code

Closing

It is fantastic to see these online APIs which tie into alternative popular websites. This advancing age of web technology allows more developers access into data systems than ever before. IMDb is just one example out of many popular websites benefitting from an external web service. Feel free to download a copy of my source code and toy around with this API for your own projects.

Exit mobile version