How To Code a Forrst API Webapp using JSON and jQuery

by Jake Rocheleau

on March 5, 2014

in Tutorials

Get the FlatPix UI Kit for only $7 - Learn More or Buy Now

Modern development APIs work like agents for sharing information to other 3rd party websites. I’ve written many past tutorials about API development to help anyone new to this process. There are so many web-based services that it’s tough picking something to grab people’s attention.

In this tutorial I want to demonstrate how we can access the Forrst API using jQuery. Some API wrappers actually require server-side code like PHP or Ruby. But it’s often easier to work with JSON objects instead. Then we can parse all the return data using client-side JavaScript. Take a look at my sample demo to see the final product.

forrst api tutorial howto preview screenshot

Building the Page

My initial HTML page is actually quite small. I’ve downloaded a local copy of jQuery along with creating an extra file named forrst-json.js. This could have been embedded into the page but since there is a lot of code, it’s simpler to move this into a separate document.

<!doctype html>
<html lang="en-US">
<head>
  <meta charset="utf-8">
  <meta http-equiv="Content-Type" content="text/html">
  <title>Forrst Posts API Webapp - DesignM.ag Demo</title>
  <meta name="author" content="Jake Rocheleau">
  <link rel="shortcut icon" href="http://designm.ag/favicon.ico">
  <link rel="icon" href="http://designm.ag/favicon.ico">
  <link rel="stylesheet" type="text/css" media="all" href="css/styles.css">
  <script type="text/javascript" src="js/jquery-1.11.0.min.js"></script>
  <script type="text/javascript" src="js/forrst-json.js"></script>
</head>

There are 2 important sections within the page body. First is the navigation menu which behaves like a set of dynamic links. Forrst actually has four categorical post types – questions, codes, snaps, and links. I’ve ignored links for the sake of this demo but you still have access to all of this information via the API request.

  <div id="w">
    <h1>Recent Forrst Posts via Ajax</h1>
    
    <nav id="menu">
      <ul class="clearfix">
        <li><a href="#questions">Questions</a></li>
        <li><a href="#snaps">Snaps</a></li>
        <li><a href="#code">Code</a></li>
      </ul>
    </nav><!-- @end #menu -->
    
    <div id="content"></div>
  </div><!-- @end #w -->

When clicking any of the menu links it will trigger a jQuery function accessing the API. We can determine which type of data is needed based on the HREF value. Forrst will return a response in JSON formatting, which is parsed and embedded into the #content div.

CSS Styles

There isn’t anything new or complicated in my stylesheet. But I’ll cover how the layout works and how I’ve chosen to display information via the JSON response.

/** page structure **/
#w {
  display: block;
  width: 760px;
  margin: 0 auto;
  background: #fff;
  padding: 5px 9px;
  -webkit-border-radius: 4px;
  -moz-border-radius: 4px;
  border-radius: 4px;
  -webkit-box-shadow: 0 1px 2px rgba(0,0,0,0.25);
  -moz-box-shadow: 0 1px 2px rgba(0,0,0,0.25);
  box-shadow: 0 1px 2px rgba(0,0,0,0.25); 
}

#menu {
  display: block;
  margin-bottom: 7px;
}
#menu ul { list-style: none; }
#menu ul li { display: block; float: left; margin-right: 10px; }
#menu ul li a {
  display: block;
  float: left;
  background: #3b7140;
  color: #b1c6b3;
  font-size: 1.4em;
  padding: 7px 15px;
  text-decoration: none;
  -webkit-border-radius: 4px;
  -moz-border-radius: 4px;
  border-radius: 4px;
}
#menu ul li a:hover, #menu ul li a.sel {
  background: #538558;
  color: #fff;
}




#content { /* no styles */ }
#content .post {
  display: block;
  margin-bottom: 55px;
}

#content .meta {
  display: block;
  font-size: 1.2em;
  line-height: 1.0em;
  margin-bottom: 2px;
  color: #6c6856;
}

.post h1 { 
  font-size: 1.65em;
}
.post ul {
  list-style-type: disc; 
  list-style-position: inside;
  margin-left: 25px;
  margin-bottom: 15px;
}
.post ol {
  list-style-type: decimal; 
  list-style-position: inside; 
  margin-left: 25px;
  margin-bottom: 15px;
}
.post ul li, .post ol li {
  display: list-item;
  margin-bottom: 11px;
  font-size: 1.3em;
}

.post .thumbshot {
  margin-right: 15px;
  margin-bottom: 12px;
}

The primary body is contained inside of a wrapper div. This stays centered on the page and holds the navigation menu, along with the content div. Each new item listed from the API is contained inside a div using the class .post.

Forrst allows users to post content with a text editor to include list items, code snippets, images, links, and other HTML content. If you plan to display this on your website it might take some extra styling to get it all functional. I’ve gone ahead to rewrite some of my ul/ol list rules and created a new class .thumbshot for each image snap.

Handling the API Request

The meat of this tutorial is really found inside forrst-json.js. The file doesn’t hold JSON code itself – we pull out the JSON information based on which link is clicked by the user.

$(function(){
  var $page   = $('#content');
  var baseapi = 'https://forrst.com/api/v2/posts/list'
  
  $('#menu ul li a').on('click', function(e){
    e.preventDefault();
    var requrl = $(this).attr('href');
    var apilink;
    
    if($(this).hasClass('sel')) return;
    else {
      $('#menu ul li a').removeClass('sel');
      $(this).addClass('sel');
    }
    
    if(requrl == '#questions') {
      apilink = baseapi + '?post_type=question';
    }
    if(requrl == '#snaps') {
      apilink = baseapi + '?post_type=snap';
    }
    if(requrl == '#code') {
      apilink = baseapi + '?post_type=code';
    }

This first section creates a variable holding the base API URI for requesting any post type. Whenever the user clicks a menu link it calls a new JS function to access the link’s HREF value. Through a series of if() logic statements the base URI is expanded with a query string(ex: ?post_type=question).

  $.ajax({
    type: 'get',
    url: apilink,
    cache: false,
    dataType: 'jsonp',
    contentType: 'application/javascript;charset=utf-8',
    beforeSend: function(xhr) {
      $page.html('<center><img src="css/loader.gif" alt="loading..."></center>');
    },
    error: function(err) { 
      console.log(err); // check console for errors
    },

When making the Ajax request we need to use JSONP as the response type. Issues with cross-domain scripting will cause problems using the JSON response type. You can read more from this SO post. I’ve written a whole long block of code so I’ll break down the first section followed by the success callback.

Since we’re using JSONP it’s better to set the content-type to application/javascript. There are a number of callback methods which fire during the Ajax process. beforeSend() creates a function that embeds a loading .gif into the page content. If there are any errors they get logged into the JavaScript console for review.

      success: function(data) {
        var list = data.resp.posts;
        var html = '';
        
        $.each(list, function(i){
          var title    = list[i].title;
          var desc     = list[i].formatted_description;
          var bcontent = list[i].content;
          var content  = list[i].formatted_content.replace('href="\/', 'href="http://forrst.com\/');
          var posturl  = list[i].post_url;
          var views    = list[i].view_count;
          var likes    = list[i].like_count;
          
          html += '<div class="post">';
          
          html += '<h2>'+title+'</h2>';
          html += '<span class="meta"><strong>Views</strong>: '+views+' - <strong>Likes</strong>: '+likes+' - <strong><a href="'+posturl+'" target="_blank">Post link</a></strong></span>';
          html += '<p>'+desc+'</p>';
          
          if(requrl != '#code' && bcontent != 0) html += '<p>'+content+'</p>';
          
          if(requrl == '#snaps') {
            // if post has pictures then we pull URLs
            var snaplist = list[i].multiposts;
            
            $.each(snaplist, function(pic){
              if(snaplist[pic].type == 'image') {
                var thumbimg = snaplist[pic].snaps.large_square_url;
                var fullimg  = snaplist[pic].snaps.original_url;
                
                html += '<a href="'+fullimg+'" target="_blank"><img src="'+thumbimg+'" width="150" height="150" class="thumbshot"></a>';
              }
            });
          }
          
          html += '</div>';
        });
        
        $page.html(html); // render new HTML onto the page
      }
    });
  });
});

This final success callback will only run after we’ve pulled some type of response from the API. It returns the most recent posts under any category along with the user information and metadata. This gets passed into the function as a single parameter. So to actually get into the object we need to access data.resp.posts and other Forrst API requests may appear similar.

Using this lone object it’s quite simple to iterate through content using jQuery $.each(). Each of the variables is targeted using the i parameter, which behaves as a numerical increment on each loop. All of the variables should be easily recognizable except for bcontent and content. The content variable has been formatted so the forward slashes are re-written(fixing the href:// links).

In various code snippets the user will include HTML right into the page. In this category it’s easier to use the plain bcontent or bare content, which is not formatted. Using a variable named html along with the JavaScript += operator I’ve combined a long string of posts after each loop.

You might find it interesting that on snap links I’ve taken the liberty of writing another $.each() loop. This runs through all the images and checks for a certain thumbnail size. These pics also get displayed into the HTML whenever browsing recent snaps. At the end of the final loop all this HTML code gets embedded into the page using jQuery’s .html() method.

forrst api tutorial howto preview screenshot

Closing

My example doesn’t utilize much of the API data for code samples. This requires a bit of string manipulation to rework the various HTML tags into entities. But keep in mind that you can access full information from any question, link, snap, or code snippet. You can also pull out API data for users and other endpoints from the website. Forrst is quite the unique online community and their API is a fantastic resource for web developers.

Powered by Shutterstock

About Jake Rocheleau

Jake is a digital researcher and writer on many popular design magazines. He frequently writes on topics including web design, user experience, mobile apps, and project management. You can find him all throughout Google and tweeting @jakerocheleau. Connect with Jake on google+