KARPACH

WEB DEVELOPER BLOG

How to get latest tweets from Twitter REST API?

My blog uses Twitter’s REST API to pull up my latest tweets to the right-side navigation. About a year ago Twitter deprecated 1.0 API and now every request needs to be authenticated. According to twitter’s documentation, I can use application-only authentication, since I am only getting tweets and don’t post anything.

Application-only authentication approach consists of two steps:

  1. Get access token from https://api.twitter.com/oauth2/token
  2. Use access token for any read-only operations (get posts, friends, followers, user information or search tweets)

I didn’t find any .NET bare-bones example that suits my needs. The code below doesn’t need any third-party libraries. It is .NET 4.5 (I used some dynamic and async / await).

Here is how you get an access token (step 1 from the above):

public async Task<string> GetAccessToken()
{           
	var httpClient = new HttpClient();
	var request = new HttpRequestMessage(HttpMethod.Post, "https://api.twitter.com/oauth2/token ");
	var customerInfo = Convert.ToBase64String(new UTF8Encoding()
							  .GetBytes(OAuthConsumerKey + ":" + OAuthConsumerSecret));
	request.Headers.Add("Authorization", "Basic " + customerInfo);
	request.Content = new StringContent("grant_type=client_credentials", 
                                            Encoding.UTF8, "application/x-www-form-urlencoded");
															  
	HttpResponseMessage response = await httpClient.SendAsync(request);

	string json = await response.Content.ReadAsStringAsync();
	var serializer = new JavaScriptSerializer();
	dynamic item = serializer.Deserialize<object>(json);
	return  item["access_token"];            
}

Here is how you get tweets:

public async Task<IEnumerable<string>> GetTweets(string userName,int count, string accessToken = null)
{
	if (accessToken == null)
	{
		accessToken = await GetAccessToken();   
	}

	var requestUserTimeline = new HttpRequestMessage(HttpMethod.Get, 
		string.Format("https://api.twitter.com/1.1/statuses/user_timeline.json?
                               count={0}&screen_name={1}&trim_user=1&exclude_replies=1", count, userName));
	requestUserTimeline.Headers.Add("Authorization", "Bearer " + accessToken);
	var httpClient = new HttpClient();
	HttpResponseMessage responseUserTimeLine = await httpClient.SendAsync(requestUserTimeline);
	var serializer = new JavaScriptSerializer();
	dynamic json = serializer.Deserialize<object>(await responseUserTimeLine.Content.ReadAsStringAsync());
	var enumerableTweets = (json as IEnumerable<dynamic>);

	if (enumerableTweets == null)
	{
		return null;
	}
	return enumerableTweets.Select(t => (string)(t["text"].ToString()));                        
}

See the complete console application at GitHub repository Twitter .NET C# Sample Application

Posted on August 18, 2014 by

Comments

Posted on 10/13/2015 01:45:24 PM by Big fan

great example thank you very much. It works fine in console, but when I try to include it into MVC web app, the code hangs at this line:

HttpResponseMessage response = await httpClient.SendAsync(request);

do you know why!?

What version of MVC you are using?

Posted on 10/13/2015 02:32:26 PM by Big fan

thanks for answering,

my MVC version is: 5.2.2.0

Try to use ConfigureAwait(false):

HttpResponseMessage response = await httpClient.SendAsync(request).ConfigureAwait(false);

Posted on 1/13/2016 12:21:19 AM by CG User

This gets me only the tweets of my user name, how can I get the tweets of other users too?

Posted on 4/8/2016 10:47:39 AM by Chris

Hi! I downloaded you app from GitHub and it works great in the console. I am trying to implement this into my MVC app. In my controller I have

this.ViewBag.Tweets = twitter.GetTweets(number, user);  
return this.View();

I am not getting past the getting of the token, why would this be?

Cheers!

Do you get an exception? How do you display tweets?

Posted on 4/8/2016 05:44:37 PM by Chris

I have fixed the issue with my controler, why are the tweets shortened and end with “…”?? Is there any way to prevent this
I don’t know

Posted on 4/25/2016 05:42:39 AM by Ramesh

Hi Chris

Pls help how can i read tweets using vb.net

Posted on 5/20/2016 04:32:37 AM by Davis Wright

Hey Chris, thanks for this post worked like charm. I tried setting the count to 3000 but it didn’t return that many record of a user who has more than 3k tweets. I am aware that the max limit is around 3200. Could you pls explain?

Thanks, Davis

Posted on 6/6/2016 12:31:11 PM by John L

Perfect! Thank you!

Posted on 6/15/2016 05:17:43 AM by sikandar

i want to get tweets of home timeline which changes needed for this?

Posted on 1/26/2017 10:45:32 PM by Werner

Thanks, this works for me.

Posted on 5/23/2017 11:52:28 PM by khanna

Here in responseUserTimeLine am getting error as authorization required …

HttpResponseMessage responseUserTimeLine = await httpClient.SendAsync(requestUserTimeline);

Plz help

Posted on 2/6/2018 11:10:26 PM by yogeshwar

hi,

want to access twitter data in android, can you please help

Posted on 9/11/2018 07:47:00 AM by Hemendra

thanks, its worked

Posted on 12/19/2018 08:06:01 PM by Awais Mushtaq

Extraordinary mate! Perfect example, simple, elegant yet effective. Very clean code. You have my salutations, sir. Thank you! If not too much to ask for, kindly, write similar code for Facebook. Like you I hate using third party wrappers. I’ll appreciate your help, sir.

Posted on 12/19/2018 10:08:46 PM by Awais Mushtaq

Please, provide code for posting tweets to user timeline. Thank you!

Posted on 11/20/2019 10:37:49 PM by Awais Mushtaq

I found it informative and simple. I wish to know how to put tweets on user time-line using same style of code. Could you please, provide something for it. Thank you very much!