Integrate Google API with your Angular application

Piotr Sobuś
6 min readApr 5, 2020

In this article, I will present how to enable and integrate Google API with your application created in Angular and use its functionalities to create and maintain different modules, e.g. display mails from your Gmail inbox or schedule events on your Google Calendar directly from your application.

Photo by Webaroo on Unsplash

In order to execute any actions related with Google within your project, your application needs to have the possibility to log-in via Google — this sounds obvious. Enabling Google Authentication can be done by Firebase or directly by Google Client library called GAPI. In my projects, I use Firebase which provides easy and flexible authentication system, real-time database and file storage. In cases of necessity of integration my application with Google API, I combine Firebase and GAPI together and the thruth is that both of these libraries get along with each other pretty well. I will skip the part of integrating your app with Firebase, there are tons of articles and tutorials how to do it and it is plain simple and of course free. If you complete this part or if you have already configured it before, you need to create credentials and enable APIs (e.g: Gmail, Calendar) you wish to have in your application in Google Console.

Create credentials and enable APIs

First, go to https://console.cloud.google.com/apis/credentials and select project you want integrate Google with. If you do not have an existing project in Google Console, just create a new one. If you have used Firebase, you will notice that your project has appeared in the drop-down list and in Select a project dialog. However, if the project did not appear in the list, just type your Firebase project ID in the search bar and your project should appear now. After selecting your project, you will notice API keys (browser and server) that were generated automatically for you. Nonetheless, we will ignore them and create our own credentials for this specific purpose.
Click Create Credentials > OAuth client ID, select Web application. In Name text field type the name of your OAuth ID (e.g: Google API). In Authorized JavaScript origins type your domain names (development or production ones — or both, for e.g: http://localhost and https://mysite.com) and click Create. A popup box will appear with your new credentials. We will only need Your Client ID for the purpose of this article, so copy it and paste it in your environment file:

export const environment = {
production: false,
// … rest of your keys
GAPI_CLIENT_ID: <YOUR CLIENT ID>
};

Next, you need to enable APIs you wish to have in your application. For instance, if you want integrate Gmail in your app, go back to Google Console and in the search bar type Gmail API, click on the first result and enable this API by clicking Enable API. Do the same operation for the rest of APIs you wish to have on-board. Lastly, you may have to configure OAuth consent screen, because you’re using a sensitive scope so your application requires verification by Google. Go to OAuth consent screen and add your desired APIs in Scopes for Google APIs section and your production domains in Authorized domains, fill the rest of the form and submit your configuration for verification. Sadly, the verification can take up some time, but good news is that you can use your APIs in development mode.

Install GAPI in your application

Go to your index.html file and include GAPI library by pasting this:

<script async defer src=”https://apis.google.com/js/api.js"></script>

Next, you need to manually declare the exported variables / functions to avoid TypeScript compilation errors. Go to your Authentication service (or if you do not have, create one) and type this after your imports.

declare var gapi: any;

Implement authentication functionality

As I said before, Firebase offers easy and flexible authentication system for Google provider, but despite this we will leave out this functionality in favor of methods provided by GAPI client library. You may ask why? To understand this, you need to know how the communication between client application and Google API works. In order to connect to Google API, send requests to it and receive data from it, you need to inject an access token in the request. An access token is a OAuth token generated each time after logging into your application. Actually, Firebase does return an access token upon log-in and yes — you can use it to send requests to Google API, but you need to keep in mind that this token has expiration time set to 1 hour. After that time, you will receive errors of code 403 from APIs you are attempting to communicate with. Having said the above, you might think —

There should be a way to refresh this token using some Firebase methods, no?

Yes and no. Firebase provides a method to refresh token, but not this particular token. You can refresh Firebase’s JWT token, which is mostly used for back-end user verification, but sadly, you cannot refresh the OAuth token. On the other hand, with GAPI you can tackle both of these issues. You can still listen for auth changes and refresh the JWT token with Firebase and you can also refresh the OAuth token (access token) with GAPI. Sounds great, doesn’t it? You only need to wrap Firebase Google Auth functionality with GAPI. So, let’s implement this in our Authentication Service.

This method initializes GAPI with configuration you have provided. In this case, it will fetch data of the user who has been authorized (name, avatar and so on) and thanks to that data, you can create a user record in your database on first log-in.

You can execute this method in your login component on a button click (for example: Login with Google). It will return a Promise with details about the user (name, e-mail, boolean flag indicating if it was a first login, etc.). After running this function, a popup will appear with your Google accounts list. Select desired account and log-in into your application. The logic behind this method is plain and simple — you will be authorized through Google API only to get the access token and data about the user’s account, additionally you will be authorized through Firebase to fetch data from the Authorization module and remain connected with Firebase and keep a persistent state of the user, so you can execute Firebase methods in parallel with GAPI methods.

Refresh access token

As I said before, the access token has an expiration time set to 1 hour and we cannot modify it — unfortunately. However, we can use an RxJS operator to run a token refresher every 30 minutes. Let’s implement it like so:

You can paste this in the constructor alongside or in your authorization mechanism and modify as you wish. You don’t have to worry about errors of code 403 now, because every 30 minutes, GAPI will create a new access token within the same session and you can just replace the new access token with the old one.

Communicate with API (example of Gmail API)

Let’s assume you have created a mail component and you wish to render a list with your messages. See how this can be done:

Conclusion

This article is a essential guide to build fundamentals on which Google communication will stand on. You can extend this functionality to a larger scope (like Google Calendar or Google Drive) and create features that can be useful for users who want to interact with Google Apps directly from your application. If you want to extend the snippet I have included, you can check Gmail API docs for more and implement as you want.

That’s it. Thanks for reading. If you liked the post, please give me an applause. If you have any questions, feel free to ask them in the comments!

--

--