Codementor Events

Step-By-Step Guide To Connect Twitter API With Angular

Published Dec 14, 2019Last updated Aug 28, 2021
Step-By-Step Guide To Connect Twitter API With Angular

APIs are one most useful tools to streamline and optimize features in an application. Using the Twitter API, you can practically access all the features of the social media platform and make your app more accessible to Twitter users.

While using any application, have you ever come across an option with you could log in or sign up or get details about your Twitter timeline on a 3rd party website? Well, all these things happen because of Twitter API.

It does not only make an application more robust but user-friendly to the end-user. In addition to that, you also need to think about the Cost To Make An App as well.

If you also want to include such features in your application, we have got a guide for you. We are going to connect Twitter API using Angular JavaScript using a step-by-step guide.

Along with the Angular, we are also going to use Node.js to create the server. You might ask that out of all of the other programming languages, why are we using Angular?

We have got our reasons along with the varied experience of the software development industry that made us believe that AngularJS is the perfect choice for this purpose.

Let’s understand why to use AngularJS.

Reasons To Use AngularJS

Excellent MVC Support

Most of the programming languages out there require developers to decompose their programs into specific model-view-controller.

Once they have written the code, they have to amalgamate everything to ensure that the program is written correctly.

But whenever you are using Angular, the program is automatically compatible with the modern-view-controller architecture. So, developers don't have to waste so much amount of time to connect the dots.

Highly Scalable

The traditional programming languages are still struggling in scaling web applications.

If you're working with CSS, HTML, and the native JavaScript, then scaling your existing web applications might be extremely tough for you.

Because it would not only result in an extended amount of code but also require additional resources and time.

However, when it comes to Angular, the way this JavaScript framework has been built makes it the best suitable for all the programming needs.

It is highly scalable yet compact to be used for building enterprise-level or necessary applications.

Reusability at its Best

Usability is one of the essential advantages of using AngularJS for programming.

All the code written in the Angular framework are entirely reusable and can be utilized for other applications as well.

Unlike other additional programming languages that make you write the whole code again, even for similar features or code every single time, AngularJS takes off that burden by making the code 100% reusable.

You can practically copy and paste your code to use it in other places effectively.

You don't need to keep writing similar code for your application. You can dynamically utilize the code and save a lot of time and resources for the application development.

Time-Saving

This is arguably my favorite reason as to why using Angular for programming needs.

Developers and entrepreneurs would agree that time when is the most vital element to ensure efficient product development.

When it comes to programming, you will have to invest a lot of time to get the required application for yourself.

Whenever you are working with HTML, CSS, or native JavaScript, the time required to build the whole application is considerably higher compared to the time necessary to create the same application using AngularJS.

Thus, the Angular JavaScript framework helps developers save a lot of time because of its optimized build.

The programming elements which take so much amount of time in the native language can be easily made using this JavaScript framework.

Cost-Effective

This is another vital advantage of using AngularJS for front end development.

Along with its faster development capability, programming style and language used to write code in Angular are heavily practiced in the programming industry.

HTML, CSS, and JavaScript developers can quickly write code in AngularJS.

Therefore, companies and agencies don't have to look for highly skilled and unique human resources because the existing web developers can comfortably write code in AngularJS.

That's why they don't have to increase the wages of the developers or go for specific developers to do the job. Moreover, they don't have to install specific hardware or software required to write code in Angular JS.

I hope these reasons are enough to make you believe that why Angular is the ideal choice for programming.

Today, we are going to build an app with Twitter API by using Node and Angular 6.

By the end of the guide, you will have a tool:

  1. That would authenticate a Twitter user
  2. That can share Tweets using the Twitter API
  3. That can read the Twitter timeline with the same API
  4. That can also give you a list of recent tweets by the authenticated user
  5. That can also get a list of tweets where the user is mentioned
  6. And I can do other few things!

So without further ado, let’s dive straight in.

Steps To Connect Twitter API With Angular

Steps-To-Connect-Twitter-API.jpg

Step 1: Install the Required Files

Before you start building an application that connects with the Twitter API using Angular, make sure that you have enough tools installed in your system.

For this particular example, we are going to use Node and Angular JavaScript frameworks.

Therefore, you need to install Node and Angular JavaScript frameworks in your computer systems. There are enormous resources available online resources that can give you practical guidance on how to install these frameworks on any system.

Step 2: Create a Node Server

First, we will build a Node server that could help us interact with Twitter API with the maximum potential.

Since we are connecting the Twitter API, we will require credentials to access the API of one of the largest social media platforms by registering an application on their official website.

You need to go app.twitter.com to register an application first.

On this landing page, you will be asked to enter necessary details like URL, application name, and description.

Once you create your application, you will be required to create unique keys for your app.

Go to Keys and Access Token to create your access token. When you go to that tab, you will find Create my access token located at the bottom of the page.

You will get four keys like below generated by the app:

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

Make Sure you have saved the values of the above keys because these values would be required in the subsequent steps.

The first thing you need to do is create a directory for the server code.

So create a .json file and write the below code to initiate npm. You also need to create a JavaScript file, which is server.js.

Below is that code snippet:

mkdir server
cd server
npm init
touch server.js

Now, we will install the Twit package to ensure secure communication with the Twitter API. Now, we will initialize all the necessary modules inside the server.js file.

Then, create an Express app by writing the below code.

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

Remember those four values we have got in the above step, and we are going to apply the same values to the Twitter package as written in the code snippet below, which will help us in the authentication process.

const api-client = new Twitter({
  consumer_key: 'CONSUMER_KEY',
  consumer_secret: 'CONSUMER_SECRET',
  access_token: 'ACCESS_TOKEN',
  access_token_secret: 'ACCESS_TOKEN_SECRET'
});

Please note that and the values which we are using as the keys in the above code snippet would be unique for all the applications.

When you created the Twitter application account, the account will assign unique keys.

Now, we will create endpoints for posting and retrieving the values from the server node.

GET statuses/home_timeline—shows the newest tweet uploaded by the users
GET statuses/home_timeline—shows tweets where the user is mentioned
POST statuses/update—it is used for sharing tweets

Now we will write the code to retrieve the tweets.

The first endpoint would be used for retrieving tweets on your timeline. Please note that we are able to write the number of tweets that we want to retrieve.

app.get('/home_timeline', (req, res) => {
    const params = { tweet_mode: 'extended', count: 10 };
   
    client
      .get(`statuses/home_timeline`, params)
      .then(timeline => {
         
        res.send(timeline);
      })
      .catch(error => {
      res.send(error);
    });
      
});

Now, with the below snippet, only those tweets will be shown where the user is mentioned.

app.get('/mentions_timeline', (req, res) => {
    const params = { tweet_mode: 'extended', count: 10 };
   
    client
      .get(`statuses/mentions_timeline`, params)
      .then(timeline => {
       
        res.send(timeline);
      })
      .catch(error => {
      res.send(error);
    });
      
});

Please note that we are not allowed to write anything on the Twitter timeline. To do that, we just need to change the value of Access permission to Read and Write.
SS1.png

In the above code snippet, we are enabling the capability to share tweets.

This code will be written on the server.js file to call the Twitter API to do the task.

app.post('/post_tweet', (req, res) => {
 
  tweet = req.body;
   
    client
      .post(`statuses/update`, tweet)
      .then(tweeting => {
        console.log(tweeting);
         
        res.send(tweeting);
      })
 
     .catch(error => {
      res.send(error);
    });
       
    
});

Now, you can go ahead and test the REST API along with Postman to make sure all the things are working perfectly fine.

So far, we have built the Node server and written foundational code to enable basic capabilities. Let’s move to the next step.

Step 3: Testing the Backend

This is important to ensure the backend is behaving as per our anticipation.

If anything goes wrong compared to what we’ve mentioned below, you might have to change your code to make it correct. Any AngularJS Web Application Development Company would advise you to give importance to this aspect.

Enter the query home_timeline. As soon as you do that, make sure you are getting something like below.
SS2.png
Here is the result of the GET request for the mentions_timeline endpoints.
SS3.png
Make sure you are also working on the Twitter bot for maximum portability. You can use the below code to create a Twitter bot for yourself.

const express = require('express');
const Twitter = require('twit');
 
const app = express();
const client = new Twitter({
  consumer_key: 'Consumer Key Here',
  consumer_secret: 'Consumer Secret Here',
  access_token: 'Access Token Here',
  access_token_secret: 'Token Secret Here'
});
 
app.use(require('cors')());
app.use(require('body-parser').json());
 
app.post('/post_tweet', (req, res) => {
 
  tweet = {status:"Hello world"};
     
    client
      .post(`statuses/update`, tweet)
      .then(timeline => {
        console.log(timeline);
         
        res.send(timeline);
      })
 
     .catch(error => {
      res.send(error);
    });
          
});
 
app.listen(3000, () => console.log('Server running'));

Step 4: Develop an Independent Angular App to Leverage the REST APIs

This is one of the crucial steps of the whole process.

Here, we are going to work on AngularJS to build a unique and basic app to conserve the REST APIs from the Node server, which we had created in the beginning.

So, create an angular app by writing the below code.

ng new client

Now, you will need to work with the Node server from where we can request data.

To do that, we will need to tell services that would be in constant connection with the Node server.

Inside the Angular application, write the below code.

ng generate service twitterservice

Now we need to declare endpoints and inject the HttpClient inside the constructor. This whole process would be done inside a single file.

So, we would be creating two files, namely twitter.service.spec.ts and twitter.service.ts.

We would edit the file twitter.service.ts by adding the required imports and all the other changes mentioned in the above paragraph.

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

To consume the REST API, we will write the below function.

export class TwitterService {
 
 api_url = 'http://localhost:3000';
  
  constructor(private http: HttpClient) { }
 
  getTimeline() {
    return this.http
      .get<any[]>(this.api_url+'/home_timeline')
      .pipe(map(data => data));
 
  }
 
  getMentions() {
    return this.http
      .get<any[]>(this.api_url+'/mentions_timeline')
      .pipe(map(data => data));
 
  }
 
}

After accessing the Twitter services, we will create two components below to do the job.

ng generate component twitter_timeline
ng generate component twitter_mentions
ng generate component tweet

Keep in mind that we have generated these components inside the app.module.ts. Now, we will declare the roots.

import { RouterModule, Routes } from '@angular/router';
 
const appRoutes: Routes = [
  {
    path: 'twitter_timeline',
    component: TwitterTimelineComponent
  },
  {
    path: 'twitter_mentions',
    component: TwitterMentionsComponent
  },
 
  {
    path: 'tweets',
    component: TweetComponent
  },
 
  { path: '',
    redirectTo: '',
    pathMatch: 'full'
  }
];

Now, render the component like below by going to app.component.html.

<mat-toolbar color="primary">
   <mat-toolbar-row>
     <!-- <span>HOME</span> -->
      <span><a href="/">HOME</a></span>
      <span class="spacer"></span>
      <span mat-button routerLink="/twitter_timeline">Timeline</span>
      <br>
      <a mat-button routerLink="/twitter_mentions">Mentions</a>
      <br>
      <a mat-button routerLink="/tweets">Tweets</a>
   </mat-toolbar-row>
</mat-toolbar>
<router-outlet></router-outlet>

Step 5: Retrieving Tweets

In this step, we’ll be aiming to get the tweets for further use. So, we would be creating components to display those tweets.

In this example, we are creating components TwitterTimelineComponent and TwitterMentionsComponent for specific purposes.

The TwitterTimelineComponent will retrieve all the recent tweets of the users who have authenticated the app.

The other component, TwitterMentionComponent, will be used to retrieve only those tweets which have a mention of the authenticated user.

First of all, go to twitter-timeline.component.ts and start working on TwitterTimelineComponent.

export class TwitterTimelineComponent implements OnInit {
   
  myTimeline: any;
 
  constructor(private api: TwitterService) { }
 
  ngOnInit() {
   this.getTwitterTimeline();
  }
   
  getTwitterTimeline(): void {
    this.api.getTimeline()
      .subscribe(
        myTimeline => {
          this.myTimeline = myTimeline;
          console.log(this.myTimeline);
        }
      )
   }
   
}

Please note that TwitterService inside the getTwitterTimeline method to pull data of the profile of the authenticated user.

Now, we would update twitter-timeline.component.html, as shown below.

<h1>Tweeter Timeline</h1>
<div *ngIf="undefined === myData">Loading...</div>
<div *ngIf="undefined !== myData">
  <div class ="card">
    <ng-container *ngFor="let tweets of myData.data">
      <h3>{{tweets.full_text
        }}
      </h3>
      <p>{{tweets.created_at}}</p>
      <p>{{tweets.user.name}}</p>
      <p>{{tweets.user.screen_name}}</p>
      <p>{{tweets.user.location}}</p>
      <p>{{tweets.user.description}}</p>
    </ng-container>
  </div>
</div>

After these steps, make sure you run your application. I’m sure you would get all the details of your tweets as soon as you run the app.

Step 6: Posting the Tweets

We are going to post the tweets from the /post_tweet endpoint. We will create a form that users will have to fill and click on submit the button at the end.

We are going to define the input types to restrict any inaccuracy for our task.

Go to tweet.component.ts and add the following code.

import { FormBuilder, FormGroup, Validators } from '@angular/forms';
 
export class TweetComponent implements OnInit {
tweetForm: FormGroup;
    
  constructor(private api: TwitterService private formBuilder: FormBuilder) { }
 
  ngOnInit() {
 
   this.tweetForm = this.formBuilder.group({
            tweetdata: ['', Validators.required]
        });
  }
 
}

We are going to use the FormBuilder module to create the status update form.

Now just update the template so that Angular would know which form to use.

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

You might have observed from the above code snippet, we have added the validators because we don’t want users to submit a blank form.

All we have to do is go to Twitter service and update The file by writing the below code.

  tweet(tweetdata: string) {
        return this.http.post<any>(`${this.api_url}/post_tweet/`, { status: tweetdata})
            .pipe(map(tweet => {
             
                alert("tweet posted")
 
                return tweet;
            }));
    }
 
}

This is going to call the API for posting to Twitter.

Now, we will update the TweetComponent, so go to tweet.component.ts and update the code as below.

export class TweetComponent implements OnInit {
tweetForm: FormGroup;
    loading = false;
    submitted = false;
    returnUrl: string;
    error = '';
 
  constructor(private api: TwitterService private formBuilder: FormBuilder) { }
 
  ngOnInit() {
 
   this.tweetForm = this.formBuilder.group({
            tweetdata: ['', Validators.required]
        });
  }
 
  get f() { return this.tweetForm.controls; }
 
    onSubmit() {
        this.submitted = true;
 
        // stop here if form is invalid
        if (this.tweetForm.invalid) {
            return;
        }
 
        this.loading = true;
        this.api.tweet(this.f.tweetdata.value)
            .pipe(first())
            .subscribe(
                data => {
                    console.log("yes")
                },
                error => {
                    this.error = error;
                    this.loading = false;
                });
    }
 
}

Now, to get all the latest tweets, all you have got to do is hit the /home_timeline endpoint. To get all the mentions, you need to go to /mentions_timeline endpoint and go to /post_tweet for the required purpose.

Conclusion

And that’s how you can connect Twitter API using AngularJS.

Feel free to let us know how are you planning to use Twitter API in your upcoming projects.

Discover and read more posts from Harikrishna Kundariya
get started
post commentsBe the first to share your opinion
Freddy Ota
2 years ago

error version 1 api twitter

Faisal
3 years ago

Its a shame that this article is a complete copy/paste from this one:
https://code.tutsplus.com/tutorials/connect-to-the-twitter-api-in-an-angular-6-app--cms-32315

Show more replies