How to get latest tweets from Twitter REST API?

My blog uses twitter 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 don't need any third party libraries. It is .NET 4.5 (I used some dynamic and async / await).

Here is how you get 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 complete console application at github repository Twitter .NET C# Sample Application


Posted on Monday, August 18, 2014 by | Comments (12) | Add Comment

Comments

Gravatar

Re: How to get latest tweets from Twitter REST API?

Did you tried https://tweetinvi.codeplex.com/
https://www.nuget.org/packages/TweetinviAPI


https://linqtotwitter.codeplex.com/
https://www.nuget.org/packages/linqtotwitter

Posted on 1/26/2015 1:35:58 PM by kiquenet #
Gravatar

No, I didn't try those packages. I prefer not to introduce unnecessary third party dependencies.

Gravatar

Re: How to get latest tweets from Twitter REST API?

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!?

Posted on 10/13/2015 1:45:24 PM by Big fan #
Gravatar

What version of MVC you are using?

Gravatar

Re: How to get latest tweets from Twitter REST API?

thanks for answering,
my MVC version is: 5.2.2.0

Posted on 10/13/2015 2:32:26 PM by Big fan #
Gravatar

Try to use ConfigureAwait(false):
HttpResponseMessage response = await httpClient.SendAsync(request).ConfigureAwait(false);

Gravatar

Re: How to get latest tweets from Twitter REST API?

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

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

Re: How to get latest tweets from Twitter REST API?

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!

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

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

Gravatar

Re: How to get latest tweets from Twitter REST API?

I have fixed the issue with my controler, why are the tweets shortened and end with "..."?? Is there any way to prevent this

Posted on 4/8/2016 5:44:37 PM by Chris #
Gravatar

I don't know

Gravatar

Re: How to get latest tweets from Twitter REST API?

Hi Chris

Pls help how can i read tweets using vb.net

Posted on 4/25/2016 5:42:39 AM by Ramesh #
Gravatar

Re: How to get latest tweets from Twitter REST API?

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 5/20/2016 4:32:37 AM by Davis Wright #
Gravatar

Re: How to get latest tweets from Twitter REST API?

Perfect! Thank you!

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

Re: How to get latest tweets from Twitter REST API?

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

Posted on 6/15/2016 5:17:43 AM by sikandar #
Gravatar

Re: How to get latest tweets from Twitter REST API?

Thanks, this works for me.

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

Re: How to get latest tweets from Twitter REST API?

Here in responseUserTimeLine am getting error as authorization required ...HttpResponseMessage responseUserTimeLine = await httpClient.SendAsync(requestUserTimeline);
Plz help

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

New Comment

Your Name:
Email (for internal use only):
Comment:
 
Code above:

Categories

Recent Tweets

  • Simon Ince's Blog: Hierarchies with HierarchyID in SQL 2008 http://t.co/xSDwiF6rRS.
  • Visual Studio 2010 WAS painfully slow - CodeProject http://t.co/Usba1x6CZy

Valid HTML5