1. Code
  2. JavaScript
  3. Angular

Connect to the Twitter API in an Angular 6 App

Scroll to top
8 min read

In this tutorial, you'll learn how to authenticate and connect to the Twitter API using Node.js and Angular 6. By the end of this tutorial, you'll have done the following:

  • authenticate with the Twitter API
  • post tweets with the Twitter API
  • read the Twitter timeline with the Twitter API
  • and more!

Create a Node Server

We will start by building a Node server which will handle interaction with the Twitter API. The first step will be to register a new app so as to obtain the credentials to start using the Twitter API.

Simply go to https://apps.twitter.com/, create a new app, and fill out all the necessary details—i.e. the app name, description, and URL. After creating your application, you will be required to create unique keys for your application. To do that, simply go to the Keys and Access Token tab and click on the Create my access token button located at the bottom of the page.

The application will generate four keys as follows:

  • Consumer Key (the API key)
  • Consumer Secret (the API secret)
  • Access Token
  • Access Token Secret

Please make note of the above keys as they will come in handy later on.

Create a directory for the server code, create a .json file by running npm init, and create a server.js file.

1
mkdir server
2
cd server
3
npm init
4
touch server.js

We will then install the twit package and the rest of the dependencies necessary to bootstrap an Express application. 

1
npm install twit body-parser cors express

The twit package will help us in interacting with the Twitter API. Next, in server.js, initialize the modules, create an Express app, and launch the server.

1
const express = require('express');
2
const Twitter = require('twit');
3
const app = express();
4
5
app.listen(3000, () => console.log('Server running'))

Authentication

We will then supply the API keys to the twit package as shown below.

1
const api-client = new Twitter({
2
  consumer_key: 'CONSUMER_KEY',
3
  consumer_secret: 'CONSUMER_SECRET',
4
  access_token: 'ACCESS_TOKEN',
5
  access_token_secret: 'ACCESS_TOKEN_SECRET'
6
});

The keys are unique to your application and are linked to your Twitter account. So when you make a request with the Twitter API, you will be the authorized user.

We will then create the endpoints for posting and retrieving tweets on our Node server.

Twitter provides the following endpoints that will enable us to interact with our Twitter timeline when retrieving and posting tweets.

  • GET statuses/home_timeline—returns the most recent tweets posted by the user and the users they follow
  • GET statuses/home_timeline—returns the most recent mentions for the authenticating user
  • POST statuses/update—used for posting tweets

Retrieving Tweets

This first endpoint will be used to retrieve the latest tweets on your timeline. We'll also specify the number of tweets we want to retrieve.

1
app.get('/home_timeline', (req, res) => {
2
    const params = { tweet_mode: 'extended', count: 10 };
3
  
4
    client
5
      .get(`statuses/home_timeline`, params)
6
      .then(timeline => {
7
        
8
        res.send(timeline);
9
      })
10
      .catch(error => {
11
      res.send(error);
12
    });
13
     
14
});

Next is the API for retrieving all the tweets where the authenticating user has been mentioned.

1
app.get('/mentions_timeline', (req, res) => {
2
    const params = { tweet_mode: 'extended', count: 10 };
3
  
4
    client
5
      .get(`statuses/mentions_timeline`, params)
6
      .then(timeline => {
7
      
8
        res.send(timeline);
9
      })
10
      .catch(error => {
11
      res.send(error);
12
    });
13
     
14
});

In order to be able to write to the Twitter timeline, we need to change the app Access permissions level to Read and write as shown below.

change the app Access permissions level to Read and writechange the app Access permissions level to Read and writechange the app Access permissions level to Read and write

Posting Tweets

Next, update the server.js file to call the API for posting tweets.

1
app.post('/post_tweet', (req, res) => {
2
3
  tweet = req.body;
4
  
5
    client
6
      .post(`statuses/update`, tweet)
7
      .then(tweeting => {
8
        console.log(tweeting);
9
        
10
        res.send(tweeting);
11
      })
12
13
     .catch(error => {
14
      res.send(error);
15
    });
16
      
17
   
18
});

We are now done with the node server, and you can now test your REST API with Postman to ensure it is working right.

Testing the Back-End

If you query the home_timeline endpoint in your API, you should see something like the following.

home_timeline endpoint in Postmanhome_timeline endpoint in Postmanhome_timeline endpoint in Postman

And here is a GET request to the mentions_timeline endpoint:

metions_timeline endpoint in Postmanmetions_timeline endpoint in Postmanmetions_timeline endpoint in Postman

The server code we have created above can also be used to create a Twitter bot. Below is an example of a basic Twitter bot that updates a user's status.

1
const express = require('express');
2
const Twitter = require('twit');
3
4
const app = express();
5
const client = new Twitter({
6
  consumer_key: 'Consumer Key Here',
7
  consumer_secret: 'Consumer  Secret  Here',
8
  access_token: 'Access Token Here',
9
  access_token_secret: 'Token  Secret Here'
10
});
11
12
13
app.use(require('cors')());
14
app.use(require('body-parser').json());
15
16
app.post('/post_tweet', (req, res) => {
17
18
  tweet = {status:"Hello world"};
19
    
20
    client
21
      .post(`statuses/update`, tweet)
22
      .then(timeline => {
23
        console.log(timeline);
24
        
25
        res.send(timeline);
26
      })
27
28
     .catch(error => {
29
      res.send(error);
30
    });
31
      
32
   
33
});
34
35
app.listen(3000, () => console.log('Server running'));
36

Build an Angular App to Consume the REST APIs

We will now start building our Angular application which will consume the APIs from our Node server.

First, create an Angular application.

1
ng new client

Twitter Service

We will start by creating a Twitter service that will make requests to the Node server. Issue the following command in the Angular application.

1
ng generate service twitterservice

This will create two files, twitter.service.ts and twitter.service.spec.ts. Open twitter.service.ts, add the required imports, declare the API endpoint, and inject the HttpClient module in the constructor.

1
api_url = 'https://localhost:3000';
2
 
3
  constructor(private http: HttpClient) { }

We will then define the functions for consuming the REST API.

1
export class TwitterService {
2
3
 api_url = 'http://localhost:3000';
4
 
5
  constructor(private http: HttpClient) { }
6
7
  getTimeline() {
8
    return this.http
9
      .get<any[]>(this.api_url+'/home_timeline')
10
      .pipe(map(data => data));
11
12
  }
13
14
  getMentions() {
15
    return this.http
16
      .get<any[]>(this.api_url+'/mentions_timeline')
17
      .pipe(map(data => data));
18
19
  }
20
21
}

Access the Twitter Service from Component.

In order to access the Twitter service from our component, we will need to generate the following components.

1
ng generate component twitter_timeline
2
ng generate component twitter_mentions
3
ng generate component tweet

Next, declare the routes for the generated components in app.module.ts.

1
import { RouterModule, Routes } from '@angular/router';
2
3
const appRoutes: Routes = [
4
  {
5
    path: 'twitter_timeline',
6
    component: TwitterTimelineComponent
7
  },
8
  {
9
    path: 'twitter_mentions',
10
    component: TwitterMentionsComponent
11
  },
12
13
  {
14
    path: 'tweets',
15
    component: TweetComponent
16
  },
17
18
  { path: '',
19
    redirectTo: '',
20
    pathMatch: 'full'
21
  }
22
];

Now open app.component.html and render the components as shown below.

1
<mat-toolbar color="primary">
2
   <mat-toolbar-row>
3
     <!--  <span>HOME</span> -->

4
      <span><a href="/">HOME</a></span>
5
      <span class="spacer"></span>

6
      <span mat-button  routerLink="/twitter_timeline">Timeline</span>

7
      <br>
8
      <a  mat-button  routerLink="/twitter_mentions">Mentions</a>

9
      <br>
10
      <a  mat-button  routerLink="/tweets">Tweets</a>

11
   </mat-toolbar-row>

12
</mat-toolbar>

13
<router-outlet></router-outlet>

14

Retrieving Tweets

We'll create two components for displaying our tweets. The TwitterTimelineComponent will display the most recent tweets from the timeline of the authenticated user, while the TwitterMentionsComponent will display all the tweets in which the authenticated user has been mentioned.

We will start with the TwitterTimelineComponent. Update twitter-timeline.component.ts as follows:

1
export class TwitterTimelineComponent implements OnInit {
2
  
3
  myTimeline: any;
4
5
  constructor(private api: TwitterService) { }
6
7
  ngOnInit() {
8
   this.getTwitterTimeline();
9
  }
10
  
11
  getTwitterTimeline(): void {
12
    this.api.getTimeline()
13
      .subscribe(
14
        myTimeline => {
15
          this.myTimeline = myTimeline;
16
          console.log(this.myTimeline);
17
        }
18
      )
19
   }
20
  
21
}

The getTwitterTimeline method uses the TwitterService to pull data from the authenticated users timeline. We then update twitter-timeline.component.html as shown below.

1
<h1>Tweeter Timeline</h1>
2
<div *ngIf="undefined === myData">Loading...</div>
3
<div *ngIf="undefined !== myData">
4
  <div class ="card">
5
    <ng-container *ngFor="let tweets of myData.data">
6
      <h3>{{tweets.full_text
7
        }}
8
      </h3>
9
      <p>{{tweets.created_at}}</p>
10
      <p>{{tweets.user.name}}</p>
11
      <p>{{tweets.user.screen_name}}</p>
12
      <p>{{tweets.user.location}}</p>
13
      <p>{{tweets.user.description}}</p>
14
    </ng-container>
15
  </div>
16
</div>
17

Here, we iterate through the array returned by the getTwitterTimeline method and display the following attributes for each tweet:

  • location
  • description
  • username
  • created_at
  • screen_name

We then move on to the TwitterMentionsComponent and update it as follows. 

1
export class TwitterMentionsComponent implements OnInit {
2
  
3
  myMentions: any;
4
5
  constructor(private api: TwitterService) { }
6
7
  ngOnInit() {
8
   this.getTwitterMentions();
9
  }
10
  
11
  getTwitterMentions(): void {
12
    this.api.getTimeline()
13
      .subscribe(
14
        myMentions => {
15
          this.myMentions = myMentions;
16
          console.log(this.myMentions);
17
        }
18
      )
19
   }
20
  
21
}

Lastly, we need to display the data from the API in the template. Update twitter-mentions.component.html as follows:

1
<h1>Tweeter Mentions</h1>
2
<div *ngIf="undefined === myData">Loading...</div>
3
<div *ngIf="undefined !== myData">
4
  <div class ="card">
5
    <ng-container *ngFor="let tweets of myData.data">
6
      <h3>{{tweets.full_text
7
        }}
8
      </h3>
9
      <p>{{tweets.created_at}}</p>
10
      <p>{{tweets.user.name}}</p>
11
      <p>{{tweets.user.screen_name}}</p>
12
      <p>{{tweets.user.location}}</p>
13
      <p>{{tweets.user.description}}</p>
14
    </ng-container>
15
  </div>
16
</div>
17

Now, when you run the app, you should see all the attributes of your tweets displayed. 

Posting Tweets

We will start with the form for posting data to the /post_tweet endpoint, where we define an input field and a submit button for posting tweets. We will use the FormBuilder module to build our status update form. Add the following code to tweet.component.ts.

1
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
2
3
export class TweetComponent implements OnInit {
4
tweetForm: FormGroup;
5
   
6
  constructor(private api: TwitterService private formBuilder: FormBuilder) { }
7
8
  ngOnInit() {
9
10
   this.tweetForm = this.formBuilder.group({
11
            tweetdata: ['', Validators.required]
12
        });
13
  }
14
15
}

Now update the template so that Angular knows which form to use.

1
<mat-card class="contact-card">
2
  <mat-card-content>
3
    <form [formGroup]="tweetForm" (ngSubmit)="onSubmit()">
4
    <mat-form-field>
5
      <input matInput placeholder="Status"  formControlName="tweetdata" class="form-control" [ngClass]="{ 'is-invalid': submitted && f.tweetdata.errors }" >
6
    </mat-form-field>
7
    <br>
8
    <div class="form-group">
9
      <button [disabled]="loading" class="btn btn-primary">TWEET</button>
10
      <img *ngIf="loading" src="https://media.giphy.com/media/3oEjI6SIIHBdRxXI40/giphy.gif" />
11
    </div>
12
    </form>
13
  </mat-card-content>
14
</mat-card>
15

As you can see above, we have added validators so that the form cannot be submitted if it is blank.

We then go on to the Twitter service and update it to include the code for posting data to the API.

1
  tweet(tweetdata: string) {
2
        return this.http.post<any>(`${this.api_url}/post_tweet/`, { status: tweetdata})
3
            .pipe(map(tweet => {
4
            
5
                alert("tweet posted")
6
7
                return tweet;
8
            }));
9
    }
10
11
}

We will then update the TweetComponent to feature the code for calling the method for posting to the Twitter API. Add the following to tweet.component.ts.

1
export class TweetComponent implements OnInit {
2
tweetForm: FormGroup;
3
    loading = false;
4
    submitted = false;
5
    returnUrl: string;
6
    error = '';
7
8
  constructor(private api: TwitterService private formBuilder: FormBuilder) { }
9
10
  ngOnInit() {
11
12
   this.tweetForm = this.formBuilder.group({
13
            tweetdata: ['', Validators.required]
14
        });
15
  }
16
17
  get f() { return this.tweetForm.controls; }
18
19
    onSubmit() {
20
        this.submitted = true;
21
22
        // stop here if form is invalid

23
        if (this.tweetForm.invalid) {
24
            return;
25
        }
26
27
        this.loading = true;
28
        this.api.tweet(this.f.tweetdata.value)
29
            .pipe(first())
30
            .subscribe(
31
                data => {
32
                    console.log("yes")
33
                },
34
                error => {
35
                    this.error = error;
36
                    this.loading = false;
37
                });
38
    }
39
40
}

You should now be able to retrieve the latest tweets by hitting the /home_timeline endpoint, retrieve your mentions via the /mentions_timeline endpoint, and post tweets via the /post_tweet endpoint. 

Conclusion

In this tutorial, you learned how to get started with the Twitter API and how to build a simple Twitter bot with just a few lines of code. You also learned how to connect with a REST API from Angular, including creating an API Service and components to interact with that service. 

To learn more about the Twitter API, head over to the Twitter Developers site and explore some of the endless possibilities.

Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.