a blog for those who code

Tuesday 24 November 2015

Fetching Twitter Trends by places in Node.js

In this post we are going to discuss about fetching twitter trends in Node.js. Many online entities like twitter, facebook etc. format their response either in JSON or XML when exposing the APIs to the developers. In this post we will create an application in Nodejs where we will make requests to Twitter's Rest Service to get the current trends by places.

Before going through the code I strongly recommend you to go through How to fetch trending tweets in Nodejs which will give you a basic idea of how to get Consumer Key and Consumer Secret Key from Twitter Apps.

Code :

var https = require('https');
var headers = {
  'User-Agent': 'Coding Defined',
  Authorization: 'Bearer ' + require('./oauth.json').access_token
};

function callTwitter(options, callback){
  https.get(options, function(response) {
    jsonHandler(response, callback);
  }).on('error', function(e) {
    console.log('Error : ' + e.message);
  })
}

var trendOptions = {
  host: 'api.twitter.com',
  path: '/1.1/trends/place.json?id=23424848',
  headers: headers
}

function jsonHandler(response, callback) {
  var json = '';
  response.setEncoding('utf8');
  if(response.statusCode === 200) {
    response.on('data', function(chunk) {
      json += chunk;
    }).on('end', function() {
      callback(JSON.parse(json));
    });
  } else {
    console.log('Error : ' + reseponse.statusCode);
  }
}

callTwitter(trendOptions, function(trendsArray) {
  var count = 0;
  trendsArray[0].trends.forEach(function(trend) {
    count++;
    console.log(count + ". " + trend.name);
  })
});

If you go through the above code, we have created a POST request with headers like user-agent, authorization, content-type and content-length. When we are getting a response with the status code of 200 ,we are adding the response to the oauthJsonFile (oauth.json). The oauth.json file will look like below

{"token_type":"bearer","access_token":"<Your_Unique_Access_Token>"}

We have created a function called jsonHandler() which will receive the response stream and convert JSON to object. Then we have created trendOptions object which will provide settings relevant to the Twitter API. As you can see in the path we have added an Id which is nothing but the places Id of India. The place_id is a place in the world. These IDs can be retrieved from geo/reverse_geocode.

Then we will create a function called callTwitter() which will show the trends by name. When we run the above code we will get the result as :


Please Like and Share CodingDefined.com Blog, if you find it interesting and helpful.

No comments:

Post a Comment