Join our HiFi mailing list to receive the latest news & updates

How to Use JSON APIs with jQuery

8 Comment(s) | Posted | by Joel Sutherland | |

One of the best features of jQuery is its simple AJAX functionality. This allows you to easily pull data from other sites and services onto your own site. Learning how to use this functionality makes it easy to integrate any number of services into your websites, making them richer and more interesting to your visitors. It will also make you less dependent on the widgets that companies provide, allowing you to create your own.

jQuery JSON APIFor this post, I am going to show how I created URL Tweet Compete, a tool that allows you to enter multiple urls into a textarea, and it then returns the number of tweets that the they have on Twitter. Be sure to try it out so that you can understand what this post is all about.

The tools uses the Topsy Otter API. This is a fun API to play around with because it is easy to understand and it doesn't require any authentication.  Additionally, it supports jsonp which is important as I will explain later.

The core call in jQuery for this project looks like this:

$.ajax({
    url: "http://otter.topsy.com/urlinfo.js?url=http://www.nytimes.com",
    dataType: 'jsonp',
    success: function(results){
        console.log(results);
    }
});

Now lets get in to the mechanics of how this works.

What are APIs? What is AJAX?

This might be old news, but it's worth covering quickly. You could read all day about APIs and AJAX, but they are also easy enough to understand in concept.

An API is a tool that makes information available to progams in a more convenient format.  As an example, humans can go to Twitter's website in their browser to see a pretty display of tweets.  The Twitter API however presents the tweets in a way that is convenient for programs.  It just gives the info.

AJAX is a phrase that roughly means "fetching information on a loaded page using Javascript".  It is an acronym with a specific meaning, but it is now used more generally.  The "X", for example, stands for XML, but now AJAX is used whenever there is any kind of dynamic content is being displayed, including JSON. Typically, AJAX is used in conjunction with an API.

So how does it work?

In the example above we are initializing an AJAX request to the Topsy API. You can see exactly what happens by checking out the URL yourself, directly: http://otter.topsy.com/urlinfo.js?url=http://www.nytimes.com As you can see, the following is shown:

ajax response

So when that request is made, some data is sent back. We're now able to use this data however we like on the page.  In the case of the URL Tweet Compete app, we're displaying the "trackback_total" value which represents the total number of tweets that have been received.

What is JSONP?

When making AJAX requests to external domains, there are a number of restrictions that apply for security reasons. JSONP is a technique to get around these restrictions. jQuery builds it into their $.ajax() method to make it easy to use.

Whenever you're using an API that is hosted on another domain, you'll need to make sure you're using the jsonp version of the API. Topsy offers an XML, JSON and JSONP version. A common mistake is attempting to use the JSON version which is impossible with javascript on another domain.

With Topsy (and many other APIs), you can select which version you want by changing the extension on your request.  For the XML version, use ".xml", for the JSON version use ".json".  Usually to get the jsonp version, you'll use either ".jsonp" or ".js".

Putting it All Together

So in order to request information from the Topsy API and display it on a page, you'll need some code like this:

$.ajax({
    url: "http://otter.topsy.com/urlinfo.js?url=http://www.nytimes.com",
    dataType: 'jsonp',
    success: function(results){
        var title = results.response.oneforty;
        var numTweets = results.response.trackback_total;
        $('#results').append(title + ' has ' + numTweets + ' tweets.');
    }
});

This code goes and fetches information about the url: http://www.nytimes.com and then displays the number of tweets it has.  Notice that we're doing the displaying within the 'success' function.  This is because we don't get the information back from our Topysy AJAX request immediately.

Instead, once it comes back, jQuery calls the success function that we define and passes in the results so that we can use them.

Hopefully this post is helpful for those new to using APIs and AJAX.  If there are any questions or comments, please leave them below!

8 Comment(s) | Posted | by Joel Sutherland | |

Comments

  1. Ross's avatar
    Ross
    | Permalink
    Thanks for this tut, Joel. Quick question: where do the params(?) "oneforty" and "trackback_total" come from in the variables? Are these part of the topsy api or a twitter convention? Thanks!
  2. Joel Sutherland's avatar
    Joel Sutherland
    | Permalink
    @ross

    That is specific to topsy, not twitter. Check out the docs of each api to learn all the different variables that they make available.
  3. Sonu's avatar
    Sonu
    | Permalink
    Cool. Interesting place I must say. I just ended up finding this place while browsing the internet for some assignment. Its a great job you people are doing. Keep Up the great job. I'll be visiting this place frequently.

    Thanks

    http://www.fabnecklaces.com/metal/titanium-necklace
  4. Webdev's avatar
    Webdev
    | Permalink
    I have successfully integrated with twitter. thanks!
  5. Lewis's avatar
    Lewis
    | Permalink
    Thanks for the post, you just filled in a blank
  6. Digital Duane's avatar
    Digital Duane
    | Permalink
    Thanks for the tutorial! I'm new at using API clients.This is my very first attempt. Is this an automatic process? I've seen one other API client instructional and it also showed how to setup the code to fetch but no info on what to do next? Do you upload it to the Https url? I'm trying to use the Parse REST API. Any insight would be most definitely appreciated.
  7. This field is required.'s avatar
    This field is required.
    | Permalink
    This field is
  8. Facebook Application Development's avatar
    Facebook Application Development
    | Permalink
    Thanks to share a great tutorial because I already read a blog which is similar t this but more complicate to understand, so thanks again.

Leave a Comment