API : Talk to Twitter API Via C#-part 1

“Tell me and I forget, teach me and I may remember, involve me and I learn.”
― Benjamin Franklin

I have involved myself in learning and exploring twitter API (More specific REST API V1.1).One very good day, i thought why should i always use the interface aka UI to read tweets or even post them? Why can’t i do this through C# Code.The same way as i was doing in the case of facebook through FQL/Graph API.

I have framed a rule that i will not use any third-party C# SDKs like Twitterizer or LinqToTwitter etc.It should be neat and clean C# code which will do all that is required.

STEP 1:  Creating an APP


  • Choose an unique name and description for your app.Provide a valid/temporary website and callback URL.
  • Once you have successfully completed the APP creation,the next step is to create API (Key/Secret) and Token (Key/Secret).You can do this by moving to API Keys tab.

Note:  Keep an eye on the App Access level.By default it is Read-Only.You can change it under Permissions tab anytime.You have to regenerate the token once the permissions are changed/modified.

  • Once you are done with this,its now time to understand the various API’s twitter provides.

Step 2 : Twitter Documentation

  • Search API

    The Search API designed for products looking to allow a user to query for Twitter content.


    The REST API enables developers to access some of the core primitives of Twitter including timelines, status updates, and user information.

  • Streaming API

    The Streaming API is the real-time sample of the Twitter Firehose. This API is for those developers with data intensive needs. If you’re looking to build a data mining product or are interested in analytics research, the Streaming API is most suited for such things.

  • In this post,i will be specifically talking about the REST API V1.1 https://dev.twitter.com/docs/api/1.1

Step 3 : Its coding time!!!

  • As REST API’s are HTTP based in the background,i thought why can’t i try with HTTPClient Class? (shipped with .NET  framework 4.5)-Provides a base class for sending HTTP requests and receiving HTTP responses from a resource identified by a URI.
  • Tried too many things but nothing worked out until i read this post Extending HttpClient with OAuth to Access Twitter
  • Following the steps mentioned in the post above,i was able to read the tweets from any twitter account. (If you see any roadblocks or find it difficult to understand the steps in the above post,please write a comment,i will help you).
  • Wait,why should i pass 4 values (API  Key aka Consumer key,API Secret key,Token Key and Token Secret key) to read tweets ?.It is very difficult to hold these values safely.The answer is bearer token.Twitter offers applications the ability to issue authenticated requests on behalf of the application itself (as opposed to on behalf of a specific user). Twitter’s implementation is based on the Client Credentials Grant flow of the OAuth 2 specification. Note that OAuth 1.0a is still required to issue requests on behalf of users.The application-only auth flow follows these steps:
    • An application encodes its consumer key and secret into a specially encoded set of credentials.
    • An application makes a request to the POST oauth2/token endpoint to exchange these credentials for a bearer token.
    • When accessing the REST API, the application uses the bearer token to authenticate.
  • Code to generate a bearer token
//Oauth Keys (Replace with values that are obtained from registering the application
var oauth_consumer_key ="Your API Key";
var oauth_consumer_secret = "Your API Secret Key";
//Token URL
var oauth_url = "https://api.twitter.com/oauth2/token";
var headerFormat = "Basic {0}";
var authHeader = string.Format(headerFormat,
Convert.ToBase64String(Encoding.UTF8.GetBytes(Uri.EscapeDataString(oauth_consumer_key) + ":" +

var postBody = "grant_type=client_credentials";

ServicePointManager.Expect100Continue = false;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(oauth_url);
request.Headers.Add("Authorization", authHeader);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";

using (Stream stream = request.GetRequestStream())
byte[] content = ASCIIEncoding.ASCII.GetBytes(postBody);
stream.Write(content, 0, content.Length);

request.Headers.Add("Accept-Encoding", "gzip");
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
Stream responseStream = new GZipStream(response.GetResponseStream(), CompressionMode.Decompress);
using (var reader = new StreamReader(responseStream))

JavaScriptSerializer js = new JavaScriptSerializer();
var objText =reader.ReadToEnd();
JObject o = JObject.Parse(objText);


Note : I tried this using HTTPClient,but it was throwing 403 forbidden error.If you are able to achieve,please post as comment.

  • After generating the bearer token( something like AAAA……..),i used the token to post a tweet to my own twitter account . No luck,i got a reply ‘401 unauthorized ‘.
  • The reason is To request data on behalf of users (like user_timeline) you need to implement the full OAuth flow. Application Only Auth is only for endpoints that don’t require user context, like GET search/tweets.

Step 4 :Comment on this post …

Stay Tuned!!! In part 2 of this post i will be implementing the full OAuth flow and will post a tweet to any twitter account (by taking user’s Permission through our APP).

Courtesy : Twitter Developers/Forum.

10 thoughts on “API : Talk to Twitter API Via C#-part 1

    1. The example which i provided here should work fine with .Net Framework 2.0 (HTTPWebRequest/Response are supported)

      Try and let me know if you face any issue.

      If you are planning to use HTTPClient then you should have .NET Framework 4.5


  1. I have tried your code but I have some errors in compiling it.

    The type or namespace name ‘JObject’ could not be found(are you missing a using directive or an assembly reference?)

    The name ‘JObject’ does not exist in the context.

    I have added already this line

    using System.Web.Script.Serialization;

    and added also the

    C:\Program Files (x86)\Microsoft Chart Controls\Assemblies\System.Windows.Forms.DataVisualization.dll

    in my references.

    Please help me on this.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s