Using C# to access the Twitter API

My last post described how to acquire Twitter OAuth keys and tokens to allow you to use Twitter’s API to access Twitter feeds. I showed how to use the request module with node.js, which has built-in support for OAuth, to request and process data.

In this blog post I will show how to do the same thing using C# and .NET using the OAuthBase class linked to from oauth.net.

Let’s start with the code to call the Twitter API:

using System;
using System.IO;
using System.Net;
using System.Text;
using OAuth;

class App {
    static void Main() {
        // URL for the API to call
        string url = "https://api.twitter.com/1.1/statuses/user_timeline.json"
            + "?screen_name=adrianba&count=5";

        // Create a http request for the API
        var webReq = (HttpWebRequest)WebRequest.Create(url);

        // Set the OAuth header
        var auth = new OAuthHeader();
        webReq.Headers.Add("Authorization",auth.getHeader(url,"GET"));

        // Echo the response to the console
        using(WebResponse webResp = webReq.GetResponse()) {
            using(StreamReader sr = new StreamReader(
                    webResp.GetResponseStream(),Encoding.GetEncoding("utf-8")
                    )) {
                Console.WriteLine(sr.ReadToEnd());
            }
        }
    }    
}

The code here is similar to the previous post. It creates a HTTP request to the API endpoint and this time simply writes the response to the console. The difference here is that we need to add the OAuth Authorization header. The magic takes place in the getHeader() method:

class OAuthHeader : OAuthBase {
    public string getHeader(string url,string method) {
        string normalizedUri;
        string normalizedParameters;

        // OAuth keys – FILL IN YOUR VALUES HERE (see this post)
        const string consumerKey = "...";
        const string consumerSecret = "...";
        const string token = "...";
        const string tokenSecret = "...";

        // Create timestamp and nonce for this request
        string timeStamp = GenerateTimeStamp();
        string nonce = GenerateNonce();

        // Generate signature for the header
        string signature = GenerateSignature(
            new Uri(url), consumerKey, consumerSecret, token, tokenSecret,
            method, timeStamp, nonce, out normalizedUri, out normalizedParameters);

        // Compose the authorization header value
        // See http://tools.ietf.org/html/rfc5849#section-3.5.1
        StringBuilder auth = new StringBuilder();
        auth.Append("OAuth ");
        auth.AppendFormat("{0}="{1}", ", OAuthConsumerKeyKey, UrlEncode(consumerKey));
        auth.AppendFormat("{0}="{1}", ", OAuthNonceKey, UrlEncode(nonce));
        auth.AppendFormat("{0}="{1}", ", OAuthSignatureKey, UrlEncode(signature));
        auth.AppendFormat("{0}="{1}", ", OAuthSignatureMethodKey, "HMAC-SHA1");
        auth.AppendFormat("{0}="{1}", ", OAuthTimestampKey, timeStamp);
        auth.AppendFormat("{0}="{1}", ", OAuthTokenKey, UrlEncode(token));
        auth.AppendFormat("{0}="{1}"", OAuthVersionKey, "1.0");
        return auth.ToString();    
    }
}

The OAuthHeader class inherits from the OAuthBase class mentioned above. This provides the GenerateTimeStamp, GenerateNonce, and GenerateSignature methods. Twitter uses the OAuth 1.0a protocol, defined in RFC5849. This specification outlines the Authorization header value that is constructed at the end of the getHeader() method.

You can keep the OAuthHeader class around for easy access to resources needing OAuth authorization such as Twitter.