JavaScript - - By Michael Wanyoike

Example Twitter JSON File

Twitter, one of the biggest social networks, has been providing developers access to their platform via a REST API for years. They also have a streaming API for developers interested in real-time data. To gain access to any of these APIs, you will need first to register an application here. Ensure you have read the Developer Agreement, otherwise you will be locked out if you create an application that violates their terms.


July 27th, 2017: This article series was rewritten with up-to-date information and fresh examples.


Once you have registered your application, you will be able to generate the following keys needed for your app to access Twitter’s data.

  • consumer key (also known as API key)
  • consumer secret
  • access token key
  • access token secret

The Twitter API uses the JSON format to communicate with third-party apps. Hence, you can use any programming language that has JSON support to develop your application. In this example, we’ll use NodeJS.

First, git clone the json-examples project, install the dependencies and create a .env file.

git@github.com:sitepoint-editors/json-examples.git
cd json-examples
npm install
touch .env

In the .env file, you’ll need to populate the following settings:

TWITTER_CONSUMER_KEY=
TWITTER_CONSUMER_SECRET=
TWITTER_ACCESS_TOKEN_KEY=
TWITTER_ACCESS_TOKEN_SECRET=

Next, let’s have a look at the twitter-json-example.js code.

require('dotenv').config();
var Twitter = require('twitter');

const CONSUMER_KEY = 'TWITTER_CONSUMER_KEY';
const CONSUMER_SECRET = 'TWITTER_CONSUMER_SECRET';
const ACCESS_TOKEN_KEY = 'TWITTER_ACCESS_TOKEN_KEY';
const ACCESS_TOKEN_SECRET = 'TWITTER_ACCESS_TOKEN_SECRET';

// Validate Twitter API Keys
const keys = [CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN_KEY, ACCESS_TOKEN_SECRET ]
keys.forEach((key) => {
  if(!process.env[key])
    throw new Error(key + ' has not been set!');
});

var client = new Twitter({
  consumer_key: process.env[CONSUMER_KEY],
  consumer_secret: process.env[CONSUMER_SECRET],
  access_token_key: process.env[ACCESS_TOKEN_KEY],
  access_token_secret: process.env[ACCESS_TOKEN_SECRET]
});

var params = {screen_name: 'sitepointJS', count: 3};
client.get('statuses/user_timeline', params, function(error, tweets, response) {
  if (!error) {
    console.log(JSON.stringify(tweets));
  }
});

To easily work with the Twitter REST API, we have enlisted the help of an npm package named Twitter. First, we validate that all API keys have been defined. We then perform a query on the path statuses/user_timeline. To learn more about Twitter API paths, check out Apigee Twitter console.

To execute the code, just do:

node twitter-json-example.js

Wait a few seconds and you’ll soon receive a JSON output. Below I’ve demonstrated the partial results:

[{
  "created_at": "Thu Jun 22 21:00:00 +0000 2017",
  "id": 877994604561387500,
  "id_str": "877994604561387520",
  "text": "Creating a Grocery List Manager Using Angular, Part 1: Add & Display Items https://t.co/xFox78juL1 #Angular",
  "truncated": false,
  "entities": {
    "hashtags": [{
      "text": "Angular",
      "indices": [103, 111]
    }],
    "symbols": [],
    "user_mentions": [],
    "urls": [{
      "url": "https://t.co/xFox78juL1",
      "expanded_url": "http://buff.ly/2sr60pf",
      "display_url": "buff.ly/2sr60pf",
      "indices": [79, 102]
    }]
  },
  "source": "<a href=\"http://bufferapp.com\" rel=\"nofollow\">Buffer</a>",
  "user": {
    "id": 772682964,
    "id_str": "772682964",
    "name": "SitePoint JavaScript",
    "screen_name": "SitePointJS",
    "location": "Melbourne, Australia",
    "description": "Keep up with JavaScript tutorials, tips, tricks and articles at SitePoint.",
    "url": "http://t.co/cCH13gqeUK",
    "entities": {
      "url": {
        "urls": [{
          "url": "http://t.co/cCH13gqeUK",
          "expanded_url": "http://sitepoint.com/javascript",
          "display_url": "sitepoint.com/javascript",
          "indices": [0, 22]
        }]
      },
      "description": {
        "urls": []
      }
    },
    "protected": false,
    "followers_count": 2145,
    "friends_count": 18,
    "listed_count": 328,
    "created_at": "Wed Aug 22 02:06:33 +0000 2012",
    "favourites_count": 57,
    "utc_offset": 43200,
    "time_zone": "Wellington",
  },
}]

Also: See more JSON examples.

Sponsors
Login or Create Account to Comment
Login Create Account