Using the Twitter API with NodeJS

There was a study done by Pew Research a number of years ago that found that ⅔ of all tweets with links to popular websites. To the average Twitter user that probably doesn’t come as a surprise.

Twitter is incredibly easy to automate, in fact, today I’m going to show you just how easy it is to use the Twitter API with NodeJS to read, search, and post tweets.

Setup Your Twitter Dev Account

Because of the sheer volume of Twitter bots, Twitter requires an application before you can use their API. While you can start using your API key as soon as you submit the application, some features might be restricted until it is reviewed.

Apply here:

https://developer.twitter.com/en/apply-for-access

Once your application is complete, navigate to your developer dashboard and create a new application. Once, you generate your application, go to settings and make sure to turn on Read and Write Permissions:

Next, head to the keys menu, and generate and copy your API and Access tokens. We’ll use them to authenticate next.

Setting Up Our Script

Since we’re going to be using NodeJS to work with the Twitter API, create a new NPM project with:

npm init

And go through the standard questions. Next, we are going to install a great wrapper for the Twitter Developer API. While this isn’t necessary, it will make authentication much cleaner.

npm install twitter-api-v2

Once that’s done, we can create and authenticate our client like so:

const {TwitterApi} = require('twitter-api-v2');

const client = new TwitterApi({
    appKey: 'INSERTKEY',
    appSecret: 'INSERTKEY',
    accessToken: 'INSERTKEY',
    accessSecret: 'INSERTKEY',
});

And of course, fill in the relevant API keys and tokens for your app.

Pulling and Posting Tweets

Now let’s showcase some of the API calls you can make.

To get data about a tweet from its ID:index.js1

client.v2.singleTweet('1455477974489251841', {
    'tweet.fields': [
        'organic_metrics',
     ],
  }).then((val) => {
    console.log(val)
}).catch((err) => {
    console.log(err)
})

In the tweet.fields you can put all the specific data you want. To get a full list of all the parameters you can use:

https://developer.twitter.com/en/docs/api-reference-index

To tweet something out programmatically:

client.v1.tweet('This tweet was written by a bot').then((val) => {
    console.log(val)
    console.log("success")
}).catch((err) => {
    console.log(err)
})

And there you go!

Use Cases

Virtually anything that you might do normally on Twitter can be done through the API. That means that any automation you might want to do is completely possible. This includes:

  • Automated Run Accounts
  • Automatically retweet certain articles based on hashtags (Aggregation accounts)
  • Track trendings topics for algorithmic trading
  • Sentiment Analysis on tweets
  • Data analysis for your company’s Twitter campaigns