A Simple Express Server and Twitter API
Tags: javascript, node, programming, webdev
Published: 2021-02-06 12:54:28


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**](https://developer.twitter.com/en/apply-for-access)
2. Some knowledge of JavaScript
3. Command Line Usage

Let's create a folder for our application:

```
mkdir TweetPuller
```

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

```
cd TweetPuller
touch .env index.js package.json
```

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
```json
{
"name": "TweetPuller",
"version": "1.0.0",
"description": "Pull Tweets",
"main": "index.js",
"engines": {
"node" : "14.x"
},
"scripts": {
"start": "node index.js"
}
}
```

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"
```

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
```
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

```javascript
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
```

Now, what we did above was used one of the [**Twitter API V2**](https://developer.twitter.com/en/docs/twitter-api/early-access) **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
```

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](https://dev-to-uploads.s3.amazonaws.com/i/u2eb3wlgpnlpwz9uvn1z.png)

### 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`.

```json
"start:auto": "nodemon index.js"
```

Then, run the following command:
```
npm run start:auto
```
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](https://oshanoshu.github.io/)

For complete code:
{% github oshanoshu/TweetPuller no-readme %}