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:
- Get access token from https://api.twitter.com/oauth2/token
- 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