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

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.

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

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.

Creating an APP

Twitter

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

Twitter Documentation

  • REST API

    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.

  • API Console

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

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

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.

(Visited 1 times, 1 visits today)

Vidyasagar MSC

Polyglot & Pragmatic Programmer

  • Faiq

    I have to use for old version of dotnet 2.0 not for 4.5 what should i do?

    • 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

  • Hey! I was hoping to use this implementation with Unity. Any word on part 2? Really great so far!

  • I am working on it…Will blog soon

  • 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 ControlsAssembliesSystem.Windows.Forms.DataVisualization.dll

    in my references.

    Please help me on this.

    • Hi,

      The dll is part of NewtonSoft.Json Nuget. Pls. add the same to your project

      • Oscar Bonachita

        Do I need to install that? Can you give me some link about it?

  • Sanjit

    Looking forward to part 2 of ‘Talk to Twitter API’, when will it be out.

    • I am working on it.Will publish soon.Thanks for asking