Using ASP.NET MVC and JavaScript to Query Twitter’s Public API

Posted by: Malcolm Sheridan , on 7/16/2010, in Category ASP.NET MVC
Views: 35228
Abstract: The following article demonstrates how to use ASP.NET and JavaScript to query Twitter's public API.
Last week I wrote an article that explained how to use ASP.NET MVC to query Twitter's public Application Programming Interface (API) which you can use and incorporate into your site if you'd like to add Twitter feeds to it. If you don't want to use MVC for this, it's possible to return Twitter data by using HTML & JavaScript. Twitter returns data in two formats, atom and json. JSON stands for JavaScript Object Notation, and as the name suggests, it is for JavaScript consumption. 
To see this in action, I'm going to create a small ASP.NET MVC 2 website, but all the heavy lifting will take place in the JavaScript. If you haven't got Microsoft Visual Studio 2010, you can download the Express edition here

To begin with, let's take a look at the Twitter's API. The documentation is here, but for a brief overview, here's what you can do:

-          search
-          trends
-          trends/current
-          trends/daily
-          trends/weekly 

I'm going to be using the search API to search Twitter. Search returns tweets in two formats, json and atom. I'll be using the json format for my code. Let's get started!
 
To begin and end with, here's the HTML code. I'll explain what's happening afterwards:
 
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">   
    <form method="get">
        <input type="button" id="GetTweets" value="Get Tweets" />
    </form>
    <div id="showTweets"></div>
 
    <script type="text/javascript" language="javascript" src="../../Scripts/jquery-1.4.2.js"></script>
    <script type="text/javascript" language="javascript" src="../../Scripts/jquery-jtemplates.js"></script>
 
    <script type="text/javascript" language="javascript">
        $(function() {
            $("#GetTweets").click(function(e) {
                e.preventDefault();               
                var url = "http://search.twitter.com/search.json?q=&ands=worldcup&rpp=5&callback=?";
                $.getJSON(url, function (tweets) {
                    $("#showTweets").setTemplateURL("/Templates/Tweets.htm").processTemplate(tweets);               
                });
            });
        });
    </script>
</asp:Content>
 
I'm using the latest jQuery library for this. The trick to making this work is using jQuery's getJSON function. But that alone would fail seeing as though we're going cross domains using ajax. Due to browser restrictions, most Ajax requests are subject to the same origin policy; the request cannot successfully retrieve data from a different domain, sub domain, or protocol by default. If the URL includes the string callback=? in the URL, the request is treated as JSONP instead. JSONP or JSON with padding is a complement to the base JSON data format, a usage pattern that allows a page to request and more meaningfully use JSON from a server other than the primary server.
 
 
Once the data has been returned, I'm using my favourite JavaScript client template engine, jTemplates, to render the data as HTML:
 
$("#showTweets").setTemplateURL("/Templates/Tweets.htm").processTemplate(tweets);
 
Here's the template for the HTML:
 
{#foreach $T.results as data}
    <p>
        <a href="http://www.twitter.com/{$T.data.from_user}" target="_blank">
            <img src="{$T.data.profile_image_url}" alt="" />
        </a>
        <br />
        <a href="http://www.twitter.com/{$T.data.from_user}" target="_blank">{$T.data.from_user}</a>
        <br />
        {$T.data.text}
        <br />
    </p>   
{#/for}
 
I love client template engines because it allows you to separate the rendering of the data from the code grabbing the data. Nice and simple.
 
If you run the application, you'll get the latest searches on the 2010 FIFA world cup from Twitter. This is a cool way of interacting with Twitter without server side code. The entire source code of this article can be downloaded over here
Give a +1 to this article if you think it was well written. Thanks!
Recommended Articles
Malcolm Sheridan is a Microsoft awarded MVP in ASP.NET, a Telerik Insider and a regular presenter at conferences and user groups throughout Australia and New Zealand. Being an ASP.NET guy, his focus is on web technologies and has been for the past 10 years. He loves working with ASP.NET MVC these days and also loves getting his hands dirty with jQuery and JavaScript. He also writes technical articles on ASP.NET for SitePoint and other various websites. Follow him on twitter @malcolmsheridan


Page copy protected against web site content infringement by Copyscape


User Feedback
Comment posted by Phil b on Friday, July 16, 2010 2:30 PM
another great article malcom. jtemplates looks slick and i am going to try it out this weekend

Post your comment
Name:  
E-mail: (Will not be displayed)
Comment:
Insert Cancel