Skip to content

Instantly share code, notes, and snippets.

@anandthakker
Created March 7, 2015 02:24
Show Gist options
  • Save anandthakker/948afa55399b1d8eff51 to your computer and use it in GitHub Desktop.
Save anandthakker/948afa55399b1d8eff51 to your computer and use it in GitHub Desktop.
Twitter search API test
// Usage: node index.js "twitter search string"
var request = require('request');
// Grab a bearer token using application-only auth
// (doc: https://dev.twitter.com/oauth/application-only)
var consumer_key = process.env.TWITTER_CONSUMER_KEY || 'CONSUMER_KEY';
var consumer_secret = process.env.TWITTER_CONSUMER_SECRET || 'CONSUMER_SECRET';
var authHeaderValue = new Buffer(
[consumer_key, consumer_secret]
.map(encodeURIComponent)
.join(':')).toString('base64');
request({
method: 'POST',
url: 'https://api.twitter.com/oauth2/token',
headers: {
'Authorization': 'Basic ' + authHeaderValue,
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
},
form: {
grant_type: 'client_credentials'
}
}, function(err, resp, body) {
// Now use the bearer token to hit the search/tweets.json endpoint, and pipe
// the results to stdout.
// (doc: https://dev.twitter.com/rest/public/search)
if(err || !resp.statusCode || resp.statusCode < 200 || resp.statusCode >= 400) {
console.error(err, resp.statusCode);
return;
}
var token = JSON.parse(body).access_token.toString('utf8');
request({
method: 'GET',
url: ' https://api.twitter.com/1.1/search/tweets.json',
qs: {
q: process.argv[2]
},
headers: {
'Authorization': 'Bearer ' + token
}
}).pipe(process.stdout);
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment