Sep 06

Retrieving Twitter Status ("Tweets") Via Twitter API Using LINQ to XML

How to retrieve your twitter status using .net and linq to xml...

I thought it would be cool to have my Twitter status show up on the site so I looked up the Twitter API documentation and got to work. It is very simple and easy to use, especially if you are just retrieving public tweets. It allows you to retrieve the timeline(s) in different formats such as JSON, XML, RSS, etc. Since I will be making the call from the server side in ASP.NET, I chose the XML format and used LINQ to XML to get the status:

public string GetTwitterStatus() {

        XDocument feed = XDocument.Load("http://twitter.com/statuses/user_timeline/r1cky.xml?count=1");

        return (from item in feed.Descendants("status")
            select item.Element("text").Value).SingleOrDefault();
    }

As you can see, the code is very similar to the code for retrieving my delicious RSS feed. Be sure to cache the result because Twitter throttles the use of the API.

If you are going to do more complex actions, like updating your status or looking up private/protected timelines, then you need to authenticate. At this point, the authentication is just Basic HTTP Auth so its not very secure but not hard to implement either ;).

Update (9/8/08): In case you need it, below is the code to parse the created_at date from the Twitter XML format.

DateTime.ParseExact(item.Element("created_at").Value, "ddd MMM dd HH:mm:ss zzz yyyy", CultureInfo.InvariantCulture);

Powered by my hackings on Django-Mingus a Django project, PostgreSQL, memcached, nginx, Apache + mod_wsgi, Ubuntu, Rackspace Cloud,...

Disclaimer: The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

html5 | top