Overview

This writing discusses the Twitter API and how you can utilize it in your managed application. It begins by a brief discussion of the API and the methods used. After that, it digs into the discussion of how you can utilize the API into your application with help of code samples and examples. At the end of this writing, there's a nice open-source Twitter client application available for download. Worth mentioning that this article focuses on the REST API set of Twitter, specifically XML endpoints.)

Introduction

Today, we are talking about Twitter as it is one of the most famous social networking services. This article discusses how you can create Twitter clients using .NET Framework. Oh, before we start, I'd like to introduce you my twitter account first J, it's @elsheimy.

Twitter API

What Twitter API is

Before we dig into the discussion of Twitter API we need to know first what the Twitter API is.

Twitter API is a set of endpoints (or methods) that allow applications to work with Twitter data.

REST API:
This is the core API set; it allows developers to access core Twitter data, it contains most (if not all) of the methods and functions you would use to utilize Twitter data in your application, and it supports (mostly) three formats (or endpoints) for each method: XML, Atom, and JSON formats.

Search API:
Fully integrating search methods allows you to search for tweets based on specific criteria and to search for daily/weekly hot trends. It supports only the JSON format. This set of API was originally developed by Summize, Inc. and integrated into the Twitter API. (Twitter is looking forward to unify the REST API.)

Streaming API:
A set of API methods that allow near-realtime access to various subsets of Twitter public statuses. All methods are in JSON format, no XML or ATOM endpoints available.

Actually, the REST API would be very sufficient for you unless you find it easier to handle the JSON format.

It is worth mentioning that the REST API provides very handful and sufficient search methods that your application can use. If you need more searching capabilities (like searching for tweets that confirm to a set of criteria,) you can dig into the REST Search API.

You are not required to stick to a specific set of API methods. You can mix the methods you like from the three APIs.

Wikipedia: REST (Representational State Transfer) is a style of software architecture for distributed hypermedia systems such as the World Wide Web.

Wikipedia: JSON (JavaScript Object Notation) is a lightweight text-based open standard designed for human-readable data interchange based on the JavaScript programming language.

API Documentation

Twitter has with a very nice API documentation that documents each and all methods and endpoints of the three parts of the API. This documentation can be found here: http://apiwiki.twitter.com.

To avoid duplication, we are not going to discuss the Twitter API again in this writing; it is already documented and available for all users. Instead, we will take a brief look at the API and discuss how we can utilize it in our .NET application. For simplicity, we will focus on XML endpoints. Therefore, all of our code would rely on the XML features of .NET Framework 2.0 (i.e. System.Xml.dll library.) Oh, you are free to write the code the way you like (e.g. integrating LINQ for XML into the code.)

Now, we are going to look inside the Twitter API.

Things to be Kept into Mind

Calls to the Twitter API are limited:
Don't expect to post unlimited updates or to follow thousands of users in just an hour! Many methods have a call limit (hourly/daily.) For example, at the time of this writing, you have only 150 API requests per hour, further requests would return an exception. In addition, you can send only 1,000 updates and 250 direct messages per day (can we remove this word "only"?) You can check Twitter limits here.

Every endpoint has its HTTP methods that need to be set (e.g. GET, POST, and DELETE) in the request. The documentation of each endpoint lists the HTTP methods required for that endpoint. For more information about HTTP and HTTP methods check the RFC 2616 Section 9 document.

API Methods

The following is a discussion about Twitter API methods and how you can call them.

Method Address

Every method has an address (i.e. URI). The address of a method is something like that: http://api.twitter.com/1/statuses/public_timeline.format (for the statuses/public timeline method.) We replace the format field with the format we like to work with (e.g. xml, atom, json.)

This method returns the 20 most recent statuses from arbitrarily-selected non-protected Twitter users; this list is called the Public Timeline. Because we have selected the XML format (or endpoint) we end up with XML data.

From the data returned we can extract the structure of statuses and users. Twitter API is good enough; it uses the same structure for all data returned. In other words, all methods (in the REST API, remember?) use the same structure (i.e. schema) to represent status and user objects. Those structures are covered soon.

Methods with Arguments

Most of methods accept arguments, some are optional and others are required. An example of a function requires a single argument is the users/show method that returns profile information about a specific user.

This function accepts one of three arguments:

id:
The ID or screen name of the user.

user_id:
The ID of the user.

screen_name:
The screen name of the user.

We set arguments the same way we set web pages query strings. Considering my twitter account @elsheimy as an example, we could query user profile using one of four ways:

Provide your Twitter username and password to pass to the results. If authentication was OK, you should receive the most recent 20 statuses of your friend timeline in the same structure (schema) as the Public Timeline method. On the other hand, if the authentication process failed, you should receive an error:

Notice that the sender and recipient are just user objects. It is worth mentioning that the direct_messages function return a list of direct_message objects (like the timeline functions that return list of status objects.)

Twitter and .NET

Now, you have a solid understanding of the Twitter API and how you can access it. Now, let's utilize this API into our .NET applications.

Accessing the API

To access the API from your .NET application you need to create a HTTP request and send it to the server and wait for server response. Let's consider an example. The following code snippet connects to the server and retrieves a System.Xml.XmlDocument that contains the returned data.

We have used the System.Xml.WebRequest class to create the request and to get the response (as an instance of System.Xml.WebResponse class) from the server. Once we get the XmlDocument, we can walk through the data and retrieve it.

Authentication

You can take one of two approaches to authorize Twitter users:

OAuth Authorization:
An authentication protocol that allows users to approve application to act on their behalf without sharing their password. As this function requires more overhead and requires your application to be registered in the Twitter clients' directory, we would better use the second approach in our examples.

Request Authorization:
To provide authentication information in each request you make to the server.

Considering a method like statuses/update method that updates the status information of the user (i.e. sends a tweet) we would develop our previous code to be like this:

Encoding URIs

Have you noticed the previous code? It tries to post the update "hello from the API". Because the text is included with the URI, special handling to the text should be carried. This special handling for text included in URIs is usually called Percent-encoding or URL Encoding. This encoding replaces unsafe characters with their hexadecimal values preceded by percentage (%) signs. Unsafe characters are those somewhat conflicted with URI special characters. For example, if we would encode the text "hello from the API" we would end up with "hello%20from%20the%20API".

There are many unsafe characters that should be percent-encoded including $, +, &, :, and =. A nice discussion of URL Encoding can be found in the article URL Encoding by Brian Wilson.

Once we get the idea, we can create our percent-encoding class that encodes/decodes strings:

For clearness, we have included the encoded string of each character along with the character itself. You don't have to do this. You can convert the character to a number and just output the number in hex format.

Now we could change the code that updates the status to the following:

.NET includes a nice function that escapes (encodes) a URI, System.Uri.EscapeUriString() function. However, this function does not encode all unsafe characters.

Business Objects

Once you know the structure of the XML data returned, you can create your business objects that would encapsulate this data. The following are the three classes that would represent our three core objects, the user, the status, and the message.

twittoo, Sample Application

twitto, is our WinForms sample application that utilizes the Twitter API. This is just a very simple application with basic functionalities.

Snapshots

The following are snapshots of the application:

Figure 2 - twitto 0

Figure 3 - twitto 1

Figure 4 - twitto 2

Figure 5 - twitto 3

Figure 6 - twitto 4

Figure 7 - twitto 5

Description

This application was created using C# and WinForms 2.0 technology; it allows the user to navigate through his friends' timeline, mentions, direct messages, retweets, and friends, and to update his status, reply to tweets, retweets, and to direct messages. Data is not refreshed automatically, the user have to click the "refresh" button. (You can create your own routine that creates a timer that updates the data automatically.)

Interface

As you see, the application uses just the Windows Common Controls all around the application; no 3rd party controls were used.

To represent a status, message, or a user, the application overuses the System.Windows.Forms.TableLayoutPanel control to represent each status, message, or user. It consists of four columns and two rows. The following figure shows how the control is laid-out.

Figure 8 - TableLayoutPanel Status Template

URL Shortening

twittoo, has a very nice feature, it allows the user to insert a shortened URL into his tweets. For this to work, the application makes use of http://is.gd URL shortening service. The following is the function that utilizes the http://is.gd API: