ocial networking has reached critical mass. One unique social networking platform, Twitter, launched in March of 2006 and took the world by storm with its social networking and microblogging platform.
The developers of Twitter had the forethought to provide a REST-based API. Numerous developers have used the API to build Twitter clients on dozens of different platforms. In this article I’ll demonstrate how to access Twitter using the .NET platform.
Twitter provides a unique communications platform. I like to think of it as a massively multi-player text messaging platform. The basic concept has three main actors: statuses (messages), followers (people who follow other people) and followees (people who are followed). Data basically flows like this: people post statuses, which are persisted into the sender’s Twitter feed and replicated into their followers’ Twitter feeds.
Anatomy of a URL
The Twitter API provides a nicely structured and highly flexible set of mechanisms for accessing the Twitter platform. You access data from Twitter by calling specific URLS which Twitter processes and then Twitter returns your data in a number of standardized formats including XML, RSS, ATOM and JSON.
The Twitter URL API consists of three main parts: request, return type, and optional parameters. Examine the following URL:
The /statuses/user_timeline portion of the message specifies the type of message (action) to process. The example message returns the timeline (last set of statuses) for a specified user.
The second part of the request is the basic parameter of the request. The sample parameter, rodpaddock, tells the statuses/user_timeline request to return my timeline.
The final parameter, .xml specifies the data format I want Twitter to return?XML format, in this case. Alternatively, to get Twitter to return a different format, I could change the extension to .rss, .json, or .atom.
Figure 1 demonstrates the data returned from the example call.
|Figure 1. Status XML: Here’s the XML Twitter returns for the sample request.
Most Twitter REST calls also support a number of optional parameters. The user_timeline request has the following optional parameters:
- id: returns messages using the posters id
- count: returns specified number of messages (default is 20, maximum is 200)
- since: returns messages since a specified date
- since-id: returns messages since a specified message id
- page: returns messages from a specified display page
When passing optional parameters to Twitter you do it just like you would when passing parameters to a web request via the URL?by placing the parameters after a question mark. As an example, the following call returns the last 200 messages from my timeline:
The following URL returns my last 200 statuses from December 1, 2008.
Twitter returns self-contained XML, meaning you don’t need to make follow up calls when dealing with XML return data. A status XML has this basic structure:
Each status record contains all the relevant data, including the details of its creator. It doesn’t get much simpler than that.
|Editor’s Note: This article was first published in the March/April 2009 issue of CoDe Magazine, and is reprinted here by permission.
The Simplest Thing that Could Possibly Work
Software guru Ward Cunningham described the concept of wikis (which he created) as the “simplest thing that could possibly work.” Talking to Twitter is just that simple?provided you have the proper tools.
The .NET Framework provides a great set of tools for accessing Twitter and you will be surprised just how simple it is. You use the .NET HttpWebRequest class partnered with a .NET StreamReader class. The following function sends a call to Twitter and stores the returned content to a string.
Function GetTweet(ByVal URL As String) _ As String Dim Request As HttpWebRequest = _ HttpWebRequest.Create(URL) Request.Method = "POST" Dim Response As WebResponse = Request.GetResponse Dim Reader As New _ StreamReader(Response.GetResponseStream) Dim Results As String = Reader.ReadToEnd Reader.Close() Response.Close() Return Results End Function
Now you have a simple function that accepts a URL and returns the results to a string. You can parse this string using the XML or JSON parser of your choice. The following code demonstrates how to query the returned statuses using basic XPATH:
Dim TwitterLib As New TwitterLib Dim URL As String =_ "http://.../statuses/user_timeline/rodpaddock.xml" Dim XML As String = TwitterLib.GetTweet(URL) Dim Doc As New XmlDocument Doc.LoadXml(XML) Dim XMLNodes As XmlNodeList = _ Doc.SelectNodes("//statuses/status/text") For Each Node As XmlNode In XMLNodes Console.WriteLine(Node.InnerText) Next
As you can see talking to Twitter is pretty simple. Now I’ll kick it up a notch.
To use a JSON object in .NET you need to add a reference to the System.Web.Extensions namespace, which contains the JsonSerializer class. After importing this assembly change the extension in your Twitter URL from .xml to .json. This causes Twitter to return the results in JSON notation. Now change your code to implement the serializer as follows:
The code in the preceding For loop shows how you can now access the data returned from Twitter in a more “object-like” manner. The first line of code references the elements on the status object itself. The second line of code shows how to access data from the user element of a status. Not too bad, eh?
Some Authorization Required
Some Twitter transactions require authentication. Posting status updates requires authentication against the Twitter API. This may sound challenging but it really isn’t. The Twitter API uses simple web authentication which you can handle with the native .NET NetworkCredential class. Listing 1 shows the code necessary to send an authenticated request to update your status.
The update status code does a little more than just the simple request. Unique aspects of this code are that it:
- Sets the Credentials property to the passed in Credentials object.
- Uses the System.Web.HttpUtility class to URL encode content sent to Twitter.
- Sets the content type and length to the proper encoding formats.
- Sets the Expect100Continue property on the System.Net.ServicePointManager. If you don’t set this Twitter will return 417 response codes that will break your code. This happens because of .NET’s default behavior of adding 100-Continue headers to all its default requests.
- Attaches the URL encoded parameters to the Web request using a StreamWriter.
Here you can see the code for calling the status update:
Dim URL As String = _ "http://../statuses/update.json" Dim Credentials As New _ NetworkCredential("XXX", "XXX") Dim DataToSend As String = "status=CoDe Mag Test" Dim TwitterLib As New TwitterLib Dim res As String = _ TwitterLib.CallTweetAuthenticated(URL, _ Credentials, DataToSend) MessageBox.Show(res)
Building a Simple Client
Now I’ll create a simple client that displays statuses on-screen. This application has two parts: a simple WPF-based ListBox to format status objects, and a class that abstracts the complexities of Twitter’s XML or JSON formats.
Listing 2 is a domain object representing a status update. It has three properties: the message text, the poster’s screen name, and the URL to the poster’s image.
Here’s the XAML for a formatted ListBox capable of showing the status updates pulled from the URL you looked at in the beginning of this article.
Finally, the following code puts it all together to both query and display the Twitter data.
The code requests the timeline for rodpaddock in JSON format, and converts the returned data to a .NET array using the JSON serializer. That array is then transformed into a list of simple POCO (Plain Old CLR Objects) which the sample WPF form displays.
You can see the final results of this in Figure 2.
|Figure 2. Simple Twitter WPF Client: Here are the results of querying Twitter for the rodpaddock timeline.
The Twitter API might look daunting at first, but with a simple set of tools and techniques you can Twitter-enable your applications in a matter of minutes. And if you are looking for something to follow on Twitter, check out the following:
For more information about programming Twitter, check out these resources: