API: Talk to Twitter API Via C# - Part 1 (2024)

“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

  • Create a twitter APP using your twitter login and by visiting https://apps.twitter.com/.

    API: Talk to Twitter API Via C# - Part 1 (1)

  • Choose a 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, it's now time to understand the various APIs 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: It's Coding Time!!!

  • As REST APIs 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 is as follows:


    //Oauth Keys (Replace with values that are obtained from registering the applicationvar oauth_consumer_key ="Your API Key";var oauth_consumer_secret = "Your API Secret Key";//Token URLvar 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) + ":" +Uri.EscapeDataString((oauth_consumer_secret)))));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 it, please post as a comment below.

  • 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).

API: Talk to Twitter API Via C# - Part 1 (2024)


Top Articles
Latest Posts
Article information

Author: Greg O'Connell

Last Updated:

Views: 5629

Rating: 4.1 / 5 (42 voted)

Reviews: 89% of readers found this page helpful

Author information

Name: Greg O'Connell

Birthday: 1992-01-10

Address: Suite 517 2436 Jefferey Pass, Shanitaside, UT 27519

Phone: +2614651609714

Job: Education Developer

Hobby: Cooking, Gambling, Pottery, Shooting, Baseball, Singing, Snowboarding

Introduction: My name is Greg O'Connell, I am a delightful, colorful, talented, kind, lively, modern, tender person who loves writing and wants to share my knowledge and understanding with you.