Twitter and Node.js, Application Auth
Application only authentication allows the application to issue requests to the twitter API without having to go to the trouble of getting user permission. Here's the docs:
https://dev.twitter.com/docs/auth/application-only-auth
We're going to need to use the OAuth2 protocol to do this and fortunately, there is a Node package for this job: oauth
First we will want to install the oauth package:
npm install oauth --save
And then require it:
var OAuth2 = require('OAuth').OAuth2;
We can now use the OAuth2 object to fetch an access token on our behalf:
var oauth2 = new OAuth2(KEY, 'SECRET', 'https://api.twitter.com/', null, 'oauth2/token', null);
oauth2.getOAuthAccessToken('', {
'grant_type': 'client_credentials'
}, function (e, access_token) {
console.log(access_token); //string that we can use to authenticate request
});
The token gets put into the headers of our HTTPS request:
var options = {
hostname: 'api.twitter.com',
path: '/1.1/statuses/user_timeline.json?screen_name=mostlyharmlessd',
headers: {
Authorization: 'Bearer ' + access_token
}
};
It's finally time to make our request using https:
https.get(options, function(result){
result.setEncoding('utf8');
result.on('data', function(data){
console.log(data); //the response!
});
});
It's not quite that simple though, the data comes back in chunks. You will need to put them all back together before parsing the response:
https.get(options, function(result){
var buffer = '';
result.setEncoding('utf8');
result.on('data', function(data){
buffer += data;
});
result.on('end', function(){
var tweets = JSON.parse(buffer);
console.log(tweets); // the tweets!
});
});
DONE!
You can see a gist for the whole of this code snippet here: https://gist.github.com/Dakuan/5899971
Written by Dominic Barker
Related protips
1 Response
Thank you, this worked for me perfectly!