Srikanth Technologies

Accessing Twitter Using Restful Web Service

Twitter.com has become one of the most popular websites in the recent past. It is in news for more than one reason. What if you want your twitter tweets (updates) to be displayed in your website. For example, I want to show my twitter tweets in this website. I have more than one way to do it. The best and the simplest is to use Restful Web Service API provided by twitter.com.

You can access tweets of any user by using the following url.

http://twitter.com/statuses/user_timeline.xml?screen_name=username&count=n
Parameter screen_name is the name of the user whose tweets you want to access and count specifies the number of tweets to be returned. The URL (user_timeline.xml) returns tweets in the form of xml. In case you want to have tweets in the form of JSON then use user_timeline.json in the URL.

Here is a web page in ASP.NET that retreives tweets of srikanthpragada and displays text and time of the tweet. I am using  WebClient class to get data from Restful web service and then use XmlDataSource and DataList to display the details.

twitterclient.aspx


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="twitterclient.aspx.cs" Inherits="twitterclient" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <h2>Twitter Tweets</h2>
    <asp:DataList ID="DataList1" runat="server" DataSourceID="XmlDataSource1">
       <ItemTemplate>
          <b><%# XPath("text") %></b>
          <br />
          <%# XPath("created_at") %>
       </ItemTemplate>
       <SeparatorTemplate>
          <hr />
       </SeparatorTemplate>
    </asp:DataList>
    <asp:XmlDataSource ID="XmlDataSource1" runat="server"></asp:XmlDataSource>
    </form>
</body>
</html>

twitterclient.aspx.cs

using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.Xml;

public partial class twitterclient : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        WebClient wc = new WebClient();

        // get recent 5 updates
        string resp = wc.DownloadString("http://twitter.com/statuses/user_timeline.xml?screen_name=srikanthpragada&ount=5");
        XmlDataSource1.Data = resp;
    }
}
Run this Asp.Net page and change screen name to your screen name to see the most recent 5 tweets posted by you. To get more information about tweets, do read the XML document provided by the service.

For more information regarding accessing Twitter using Rest API, visit Twitter API Documentation.