DEV Community

Cover image for A Simple Express Server and Twitter API
Oshan Upreti
Oshan Upreti

Posted on • Edited on

A Simple Express Server and Twitter API

We'll create a simple Express server to get recent tweet information from a given user.

Prerequisites:

  1. You need to have a Twitter Developer Account. To learn more about it: Click Here
  2. Some knowledge of JavaScript
  3. Command Line Usage

Let's create a folder for our application:

mkdir TweetPuller
Enter fullscreen mode Exit fullscreen mode

Now, let's add some files in the folder to start with.

cd TweetPuller
touch .env index.js package.json
Enter fullscreen mode Exit fullscreen mode

Basically, package.json holds information like dependencies, name of your application, description, and start scripts. So, let's populate the package.json in a simple way.

package.json

{
"name": "TweetPuller",
"version": "1.0.0",
"description": "Pull Tweets",
"main": "index.js",
"engines": {
"node" : "14.x"
},
"scripts": {
"start": "node index.js"
}
}
Enter fullscreen mode Exit fullscreen mode

That should do it. Then, we also created a .env file where we generally store environment variables. If you are working with secret keys, you should never expose it in your application code. So, basically, you can store your secret keys/credentials in your .env file. In our case, we'll store the Bearer Token we get from your Twitter Developer Portal. And, in case we chose to publish this project on GitHub, we will use gitignore to ignore this file while committing.

.env

BEARER_TOKEN="XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
Enter fullscreen mode Exit fullscreen mode

Now, let's go ahead and install some dependencies that we will be using in our application. Once we install these dependencies, our package.json is getting populated. So, stay cool.

npm install express dotenv needle
Enter fullscreen mode Exit fullscreen mode

We are installing express because we are creating an Express server. Express is just a Node.js web application framework. We are installing dotenv to get environment variables from the .env file. We are installing needle to make Twitter API calls.

index.js

const express = require("express");
const dotenv = require("dotenv");
const needle = require("needle");


const app = express()


dotenv.config();

//Get Bearer Token from .env 
const BearerToken = process.env.BEARER_TOKEN;

const endpointUrl = "https://api.twitter.com/2/tweets/search/recent";

//Get Tweets from Twitter API
const getTweets = async(id) => {

    const params = {
        'query': 'from:'+id+' -is:retweet',
        'tweet.fields': 'created_at',
        'expansions': 'author_id'
    }
    const response = await needle ('get', endpointUrl, params,{
        headers: {
            "User-Agent": "v2RecentSearchJS",
            "authorization": `Bearer ${BearerToken}`
        }
    })

    if (response.statusCode !== 200) {
        if (response.statusCode === 403) {
            res.status(403).send(response.body);
        } 
        else {
            throw new Error(response.body.error.message);
        }
    }
    if (response.body)
        return response.body;
    else
        throw new Error("Unsuccessful Request");   
}

//This returns the object to client
const getTweetAnalysis = async(req, res) => {
    try {
        let twitterData =await getTweets(req.params.id);
        //res.send(twitterData);
        res.send(await analyze(twitterData));
    } catch (error) {
        res.send(error);
    }

}

//Simple Analysis
const twitterObject = {}
const analyze = async(twitterData) =>
{
    twitterObject["username"] = twitterData.includes.users[0].username;
    twitterObject["name"] = twitterData.includes.users[0].name;
    console.log(twitterData.data[0].text)
    let averageCharacter = 0;
    let averageWord = 0;
    let totalCharacter = 0;
    let totalWord = 0;
    let texts = twitterData.data;
    if(texts)
    {
        for(let index =0 ; index < twitterData.data.length ; index++)
        {
            totalCharacter += texts[index].text.length;
            totalWord += texts[index].text.split(" ").length;
        }
    }
    if(twitterData.meta.result_count > 0)
    {
        twitterObject["usesActively"] =  true;
        averageCharacter = totalCharacter/twitterData.meta.result_count;
        averageWord = totalWord/twitterData.meta.result_count;
    }
    else
    {
        twitterObject["usesActively"] =  false;
    }
    twitterObject["averageWordCount"] = averageWord;
    twitterObject["averageCharacterCount"] = averageCharacter;
    return twitterObject;
}

//API route 
app.get("/api/tweet/:id",getTweetAnalysis);

//You can specify the port in .env file
app.listen(process.env.PORT||3000,()=>
{
    console.log('Currently Listening to the Server')
})

module.exports = app
Enter fullscreen mode Exit fullscreen mode

Now, what we did above was used one of the Twitter API V2 Search Tweets to search for recent tweets by username. And, in turn, created an Express server to analyze the tweets and provide some information via API endpoints.

To run the server, run the following command:

npm start
Enter fullscreen mode Exit fullscreen mode

Now, you can hook this up with your client-side or you can use an application like Postman to test the server.
Screenshot of Postman API call

Extra Tip

You can install nodemon dependency to automate the server restart every time you make changes in the code.
You need to add this in the script of package.json.

"start:auto": "nodemon index.js"
Enter fullscreen mode Exit fullscreen mode

Then, run the following command:

npm run start:auto
Enter fullscreen mode Exit fullscreen mode

You should be able to build an Express server that makes calls using the get method from scratch.

Next time, we'll create the server using the database and do some post and delete calls.

You can also find this on Oshan Upreti Blog

For complete code:

Top comments (0)