How to Use JSON APIs with jQuery
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.
For 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:
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!
Comments
Karan
Can someone please explain what is meant by datatype 'jsonp'Adrian
Nice, simplified explanation. Still helping noobs like me 6 years later!Christophe
Hi,As a complete beginner (no development background, I am actually coming from the operations, but I implemented softwares much more as a project manager), I need to get data from online apps (like timecamp per instance) and to do that, I have to use JQUERY to get data via the API of Time Camp - if I understood well so far...
Can somebody help me and give me some guidance where i can find a simple tuto to use JQUERY with API in order to extract data that I can send to dashboard reports (like tableau software per instance?) in excel format or other.
If this is not clear (pardon my entry level), dont hesitate to ask me more. If someone can find me a good tuto, I would be much happy - hard to find...
Thank you!
Peter Drinnan
I've been up to my eyeballs in JSON lately. Never heard of JSONP until now. I guess all those facebook, google website plugins must use it. A lot better than using hidden iframes. Lot to learn for me still. Thanks for the article.Facebook Application Development
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.This field is required.
This field isDigital Duane
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.Lewis
Thanks for the post, you just filled in a blankWebdev
I have successfully integrated with twitter. thanks!Sonu
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
Joel Sutherland NMC team member
@rossThat is specific to topsy, not twitter. Check out the docs of each api to learn all the different variables that they make available.
Ross
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!Leave a comment