Chapter 2. Twitter API Binding

Spring.NET Social Twitter offers integration with Twitter's REST API through the ITwitter interface and its implementation, TwitterTemplate.

Creating an instance of TwitterTemplate involves invoking its constructor, passing in the application's OAuth credentials and an access token/secret pair authorizing the application to act on a user's behalf.
For example:

string consumerKey = "..."; // The application's consumer key
string consumerSecret = "..."; // The application's consumer secret
string accessToken = "..."; // The access token granted after OAuth authorization
string accessTokenSecret = "..."; // The access token secret granted after OAuth authorization
ITwitter twitter = new TwitterTemplate(consumerKey, consumerSecret, accessToken, accessTokenSecret);

You can also get an instance of ITwitter from the TwitterServiceProvider class.
The example code below shows use of the TwitterServiceProvider to retrieve an instance of ITwitter after authenticating through OAuth1 server-side flow:

TwitterServiceProvider serviceProvider = new TwitterServiceProvider("consumerKey", "consumerSecret");
OAuth1Operations oauthOperations = serviceProvider.AuthOperations;
OAuthToken requestToken = oauthOperations.FetchRequestToken("https://my-callback-url", null);
string authorizeUrl = oauthOperations.BuildAuthorizeUrl(requestToken, null);

// upon receiving the callback from the provider:
OAuthToken accessToken = oauthOperations.ExchangeForAccessToken(new AuthorizedRequestToken(requestToken, oauthVerifier), null);
ITwitter twitterApi = serviceProvider.GetApi(accessToken.Value, accessToken.Secret);

Once you have a ITwitter, you can perform a several operations against Twitter.
ITwitter is defined as follows:

public interface ITwitter : IApiBinding
  IBlockOperations BlockOperations { get; }

  IDirectMessageOperations DirectMessageOperations { get; }

  IFriendOperations FriendOperations { get; }

  IGeoOperations GeoOperations { get; }

  IListOperations ListOperations { get; }
  ISearchOperations SearchOperations { get; }

  ITimelineOperations TimelineOperations { get; }

  IUserOperations UserOperations { get; }

  IRestOperations RestOperations { get; }

The first eight properties return sub-APIs, partitioning the Twitter service API into divisions targeting specific facets of Twitter functionality. These sub-APIs are defined by interfaces described in Table 2.1, “Twitter's Sub-APIs”.
The last property RestOperations gets the underlying RestTemplate object allowing for consumption of Twitter endpoints that may not be otherwise covered by the API binding.

Table 2.1. Twitter's Sub-APIs
Sub-API InterfaceDescription
BlockOperationsBlocking and unblocking other users.
DirectMessageOperationsReading and sending direct messages.
FriendOperationsRetrieving a user's list of friends and followers and following/unfollowing users.
GeoOperationsWorking with locations.
ListOperationsMaintaining, subscribing to, and unsubscribing from user lists
SearchOperationsSearching tweets and viewing search trends
TimelineOperationsReading timelines and posting tweets.
UserOperationsRetrieving user profile data.

There are 3 ways to call a method depending on the target Framework:

What follows is a survey of common tasks you may perform with ITwitter and its sub-APIs.
For complete details on the Spring.NET Social's entire Twitter API binding, refer to the API documentation.
Samples are provided in the 'examples' directory of the distribution.

2.1. Retrieving a user's Twitter profile data

To get a user's Twitter profile, call UserOperations' GetUserProfile():

TwitterProfile profile = twitter.UserOperations.GetUserProfile();

This returns a TwitterProfile object containing profile data for the authenticated user. This profile information includes the user's Twitter screen name, their name, location, description, and the date that they created their Twitter account. Also included is a URL to their profile image.

If you want to retrieve the user profile for a specific user other than the authenticated user, you can so do by passing the user's screen name as a parameter to GetUserProfile():

TwitterProfile profile = twitter.UserOperations.GetUserProfile("brbaia");

2.2. Tweeting

To post a message to Twitter the simplest thing to do is to pass the message to the UpdateStatus() method provided by ITimelineOperations:

twitter.TimelineOperations.UpdateStatus("Spring.NET Social is awesome!")

Optionally, you may also include metadata about the tweet, such as the location (latitude and longitude) you are tweeting from. For that, pass in a StatusDetails object, setting the location property:

StatusDetails statusDetails = new StatusDetails()
  Latitude = 51.502,
  Longitude = -0.126
twitter.TimelineOperations.UpdateStatus("I'm tweeting from London!", statusDetails);

To have Twitter display the location in a map (on the Twitter web site) then you should also set the DisplayCoordinates property to true:

StatusDetails statusDetails = new StatusDetails()
  Latitude = 51.502,
  Longitude = -0.126,
  DisplayCoordinates = true;
twitter.TimelineOperations.UpdateStatus("I'm tweeting from London!", statusDetails);

If you'd like to retweet another tweet (perhaps one found while searching or reading the Twitter timeline), call the Retweet() method, passing in the ID of the tweet to be retweeted:

long tweetId = tweet.ID;

2.3. Reading Twitter timelines

From a Twitter user's perspective, Twitter organizes tweets into two different timelines:

  • User - Includes tweets posted by the user.

  • Home - Includes tweets from the user's timeline and the timeline of anyone that they follow.

To be clear, the only difference between the home timeline and the friends timeline is that the friends timeline excludes retweets.

ITimelineOperations also supports reading of tweets from one of the available Twitter timelines.
To retrieve the 20 most recent tweets from the public timeline, use the GetPublicTimeline() method:

IList<Tweet> tweets = twitter.TimelineOperations.GetPublicTimeline();

GetHomeTimeline() retrieves the 20 most recent tweets from the user's home timeline:

IList<Tweet> tweets = twitter.TimelineOperations.GetHomeTimeline();

To get tweets from the authenticating user's own timeline, call the GetUserTimeline() method:

IList<Tweet> tweets = twitter.TimelineOperations.GetUserTimeline();

If you'd like to retrieve the 20 most recent tweets from a specific user's timeline (not necessarily the authenticating user's timeline), pass the user's screen name in as a parameter to GetUserTimeline():

IList<Tweet> tweets = twitter.TimelineOperations.GetUserTimeline("rclarkson");

In addition to the four Twitter timelines, you may also want to get a list of tweets mentioning the user. The GetMentions() method returns the 20 most recent tweets that mention the authenticating user:

IList<Tweet> tweets = twitter.TimelineOperations.GetMentions();

2.4. Friends and Followers

A key social concept in Twitter is the ability for one user to "follow" another user. The followed user's tweets will appear in the following user's home and friends timelines.
To follow a user on behalf of the authenticating user, call the IFriendOperations' Follow() method:


Similarly, you may stop following a user using the Unfollow() method:


If you want to see who a particular user is following, use the GetFriends() method:

IList<TwitterProfile> friends = twitter.FriendOperations.GetFriends("braia");

On the other hand, you may be interested in seeing who is following a given user. In that case the GetFollowers() method may be useful:

IList<TwitterProfile> followers = twitter.FriendOperations.GetFollowers("braia");

2.5. Twitter User Lists

In addition to following other users, Twitter provides the ability for users to collect users in lists, regardless of whether or not they are being followed.
These lists may be private to the use who created them or may be public for others to read and subscribe to.

To create a new list, use IListOperations' CreateList() method:

UserList familyList = twitter.ListOperations.CreateList("My Family", "Tweets from my immediate family members", false);

CreateList() takes three parameters and returns a UserList object representing the newly created list.
The first parameter is the name of the list.
The second parameter is a brief description of the list.
The final parameter is a boolean indicating whether or not the list is public.
Here, false indicates that the list should be private.

Once the list is created, you may add members to the list by calling the AddToList() method:

twitter.ListOperations.AddToList(familyList.Slug, "artnames");

The first parameter given to AddToList() is the list slug (which is readily available from the UserList object).
The second parameter is the screen name of a user to add to the list.

To remove a member from a list, pass the same parameters to RemovedFromList():

twitter.ListOperations.RemoveFromList(familyList.Slug, "artnames");

You can also subscribe to a list on behalf of the authenticating user. Subscribing to a list has the effect of including tweets from the list's members in the user's home timeline.
The Subscribe() method is used to subscribe to a list:

twitter.ListOperations.Subscribe("brbaia", "music");

Here, Subscribe() is given the list owner's screen name ("brbaia") and the list slug ("music").

Similarly, you may unsubscribe from a list with the Unsubscribe() method:

twitter.ListOperations.Unsubscribe("brbaia", "music");

2.6. Searching Twitter

ISearchOperations enables you to search the public timeline for tweets containing some text through its Search() method.

For example, to search for tweets containing "#Spring.NET":

SearchResults results = twitter.SearchOperations.Search("#Spring.NET");

The Search() method will return a SearchResults object that includes a list of 50 most recent matching tweets as well as some metadata concerning the result set.
The metadata includes the maximum tweet ID in the search results list as well as the ID of a tweet that precedes the resulting tweets.
The sinceId and maxId properties effectively define the boundaries of the result set.

To gain better control over the paging of results, you may choose to confine the bounds of the search results to fit between two tweet IDs, you may pass in the since and maximum tweet ID values to Search():

SearchResults results = twitter.SearchOperations.Search("#Spring.NET", 10, 145962, 210112);

This ensures that the result set will not contain any tweets posted before the tweet whose ID is 146962 nor any tweets posted after the tweet whose ID is 210112.

2.7. Sending and receiving direct messages

In addition to posting tweets to the public timelines, Twitter also supports sending of private messages directly to a given user. IDirectMessageOperations's SendDirectMessage() method can be used to send a direct message to another user:

twitter.DirectMessageOperations.SendDirectMessage("kdonald", "You going to the Dolphins game?")

IDirectMessageOperations can also be used to read direct messages received by the authenticating user through its GetDirectMessagesReceived() method:

IList<DirectMessage> twitter.DirectMessageOperations.GetDirectMessagesReceived();

GetDirectMessagesReceived() will return the 20 most recently received direct messages.