This article will present a Git repository I created that can fetch tweets from Twitter using Twitter Api v1.1 and Node and Express. Or also known as Node.js and Express.Js.
First off, Twitter now enforces all API calls to be authenticated. To be able to call the Twitter API, there are four values you must retrieve for the App you have created at
https://developer.twitter.com/en/apps. These are:
- Consumer API
- Consumer API secret
- Access token
- Access token secret
The Git repo I created is available here:
https://github.com/toreaurstadboss/SimpleTwitterFeedExpressJs
The solution is started using:
npm run start
But for working with the solution, use
nodemon command.
The server.js is the primary part. Here we create the Express.Js server object for Node which will host our web service calls for the Tweets.
We use the following Npm libraries:
- express (web server)
- fs (FileStream for Node
- https (for secured communication
- Twitter (for Twitter API v1.1 communication
The following Js script is the server.js file:
var express = require("express");
var request = require("request");
let config = require("./config");
const https = require("https");
const fs = require("fs");
var url = require("url");
var Twitter = require("twitter");
var key = fs.readFileSync(__dirname + "/certs/selfsigned.key");
var cert = fs.readFileSync(__dirname + "/certs/selfsigned.crt");
const port = 3000;
var options = {
key: key,
cert: cert
};
var app = express();
var client = new Twitter(config);
app.get("/", function(req, res) {
res.sendFile(__dirname + "/index.html");
});
function getTweets(userName, tweetCount, res) {
var params = {
q: userName,
count: tweetCount
};
var responseFromTwitter = {};
let tweetSearched = false;
// Initiate your search using the above paramaters
client.get("search/tweets", params, function(err, data, response) {
console.log("Found # Tweets: " + data.statuses.length);
res.charset = "utf-8";
res.append("Content-Type", "application/json; charset=utf-8");
// If there is no error, proceed
if (!err) {
res.end(JSON.stringify(data.statuses));
}
});
}
app.get("/tweets/:username", function(req, res) {
let tweetsFound = getTweets(req.params.username, 10, res);
console.log(tweetsFound);
});
app.use("/css", express.static(__dirname + "/node_modules/bootstrap/dist/css"));
var server = https.createServer(options, app);
server.listen(port, () => {
console.log("server starting on port: " + port);
});
Make note that this sample uses HTTPS communication. It is using self signed certificates. I created these using this command inside Windows Subsystem for Linux:
sudo openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout ./selfsigned.key -out selfsigned.crt
This created the key pair of the selfsigned key and the certificate.
The HTTPS server is created using this:
var server = https.createServer(options, app);
server.listen(port, () => {
console.log("server starting on port: " + port);
});
The bulk of the code retrieving the Tweets is the method getTweets. We pass on the response object and use the end method of Express to stringify the JSON data we found.
I have not done much error handling here. We return data as Json if we found some Tweets for given username.
There is one route defined in Express here:
app.get("/tweets/:username", function(req, res) {
let tweetsFound = getTweets(req.params.username, 10, res);
console.log(tweetsFound);
});
The method getTweets will then retrieve data from Twitter using a HTTPS call to
function getTweets(userName, tweetCount, res) {
var params = {
q: userName,
count: tweetCount
};
var responseFromTwitter = {};
let tweetSearched = false;
// Initiate your search using the above paramaters
client.get("search/tweets", params, function(err, data, response) {
console.log("Found # Tweets: " + data.statuses.length);
res.charset = "utf-8";
res.append("Content-Type", "application/json; charset=utf-8");
// If there is no error, proceed
if (!err) {
res.end(JSON.stringify(data.statuses));
}
});
}
To test out this code, you can enter the following command to clone the repository.
git clone https://github.com/toreaurstadboss/SimpleTwitterFeedExpressJs.git
No comments:
Post a Comment