Click here to Skip to main content
Click here to Skip to main content
Technical Blog

Tagged as

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

, 18 Feb 2014 CPOL
Rate this:
Please Sign up or sign in to vote.
“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? [&#8

Editorial Note

This article appears in the Third Party Product Reviews section. Articles in this section are for the members only and must not be used by tool vendors to promote or advertise products in any way, shape or form. Please report any spam or advertising.

“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

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.

Step 2 : Twitter Documentation

  • Search API

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

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

  • 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) + ":" +
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,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).

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Vidyasagar MSC
Software Developer (Senior)
India India
Microsoft MVP (Games for Windows)
Developer | Blogger | Mentor | Gamer
Coder by profession | Gamer By Heart
Technical Blog : http://onestopdotnet.wordpress.com/
About me: http://about.me/mscvidyasagar
Follow on   Twitter

Comments and Discussions

 
QuestionFull Code PinmemberGeorge0430-Sep-14 21:32 
AnswerRe: Full Code PinprofessionalVidyasagar MSC8-Oct-14 4:48 
QuestionHttpClient PinmemberMember 86706217-Aug-14 11:58 
AnswerRe: HttpClient PinprofessionalVidyasagar MSC7-Aug-14 19:10 
QuestionFInd the Working Code Pinmembersrinivasmuriki18-Feb-14 23:45 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.150326.1 | Last Updated 18 Feb 2014
Article Copyright 2014 by Vidyasagar MSC
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid