Avav Smith

Avav Smith

1573003023

How to use Google's fully typed API SDK in Angular web application

Motivation

Task: We need to access/display events of a private google calendar.
Problem: You cannot put private calendar into an iframe or query its events using just an API key.
Requirements: Compatible with Angular, TypeScript support(service wrappers/classes and data model types)
Solution: There’s google-api-nodejs-client that provides all we need

Google’s officially supported Node.js client library for accessing Google APIs. Support for authorization and authentication with OAuth 2.0, API Keys and JWT is included.

Now to figure out how to replace that Node.js part with Angular .

Integration

Unfortunately, this library is for NodeJS and there is a slight problem integrating it into “Webpack built apps” and that includes Angular as it relies on some of the NodeJS things that don’t exist in Browser.
That is not going to stop us as there is a workaround (discussed here).

First, we need to extend a Webpack build.

npm i -D @angular-builders/custom-webpack

Then we need to replace builder in angular.json project architect configuration file, we also include a path to a custom Webpack config in options:

"architect": {
  "build": {
    "builder": "@angular-builders/custom-webpack:browser",
    "options": {
      "customWebpackConfig": {
        "path": "./extra-webpack.config.js"
      },
      ...
    },
    ...
  },
  "serve": {
    "builder": "@angular-builders/custom-webpack:dev-server",
    ...
  },
}

Explanations can be found in Angular’s builder docs.

The “hack”

Now, what is the actual “hack”? We are about to pretend all these things this NodeJS library needs exist in the browser.

  1. Simulate some of the NodeJS runtime internals like global and Buffer
  2. We have to mock a few libs that are required in runtime fs, child_process and https-proxy-agent

Providing fallbacks for global and Buffer

Add the following polyfills under the application imports in your src/polyfills.ts.

import * as process from 'process';
(window as any).process = process;
import { Buffer } from 'buffer';
(window as any).Buffer = Buffer;

Don’t forget to install these packages with npm i -D process buffer .

Put this to your index.html <head> tag. It will get rid of errors related to accessing the global as it substitutes it with the window.

<script>
  if (global === undefined) {
    var global = window;
  }"
</script>

Mocking the libraries

const path = require('path');
module.exports = {
  resolve: {
    extensions: ['.js'],
    alias: {
      fs: path.resolve(__dirname, 'src/mocks/fs.mock.js'),
      child_process: path.resolve(
        __dirname,
        'src/mocks/child_process.mock.js'
      ),
      'https-proxy-agent': path.resolve(
        __dirname,
        'src/mocks/https-proxy-agent.mock.js',
      ),
    },
  },
};

Explanation of what’s going on would be that we are telling WebPack to replace one import (file) with another. You can notice we put all the “mock” files to src/mock so it is easier to understand what these files are to our colleagues working on a project.

The code inside of these mocks is rather simple. We just need to add a few methods that are used but not required, so they can “do” nothing.
Both fs andchild_process will look like this.

module.exports = {
  readFileSync() {},
  readFile() {},
};

The https-proxy-agent is even simpler as it can be just
module.exports = {};.

Setting up the access

  1. Create a new GCP project or use an existing one.
  2. At GCP console select your project and go to the Library tab and enable API you want to use (in our case it is Google Calendar and Analytics)
  3. Customize your OAuth consent screen (name, restrictions,…)
    • set all Scopes for Google APIs you need (calendar, analytics, …)
  4. Create OAuth credentials
    • needed if when accessing private data (like calendar events or analytics)
  5. Proceed to Authentication and use the public and private OAuth keys

Authentication

You can access a lot of public data from API easily with an API key. Things like public calendars, but as long as you need some private data (private calendar for example) you will need to authenticate. That can be done via OAuth client.

Provide Google’s OAuth2Client in your app.module.ts providers array. It should look like this:

{
  provide: OAuth2Client,
  useValue: new OAuth2Client(
// You get this in GCP project credentials
    environment.G_API_CLIENT_ID,
    environment.G_API_CLIENT_SECRET,
// URL where you'll handle succesful authentication
    environment.G_API_REDIRECT,
),
},

We will be using redirect based auth so next thing is generating auth URL.

window.location.href = this.oauth2Client.generateAuthUrl({
// 'offline' also gets refresh_token  
  access_type: 'offline',
// put any scopes you need there, 
  scope: [
    // in the first example we want to read calendar events
    'https://www.googleapis.com/auth/calendar.events.readonly',
    'https://www.googleapis.com/auth/calendar.readonly',
    // in the second example we read analytics data
    'https://www.googleapis.com/auth/analytics.readonly',
  ],
});

Thanks to refresh_token OAuthClient should be able to handle token exchange even after it is expired so we don’t have to go through google’s Auth screen every hour after token expiration.

Example usages

If you like exploring documentation you visit google-apis docs or have a look on Calendar as our it is used in the example below.

Using the Calendar Service SDK

Permissions

Make sure that the account you are using does have access to the calendar you want to read events from.

Code Example

Provide Calendar class with the default auth method, in our case it is OAuth. Extend your app.module.ts providers array with this:

{
  provide: calendar_v3.Calendar,
  useFactory: 
    (auth: OAuth2Client) => new calendar_v3.Calendar({ auth }),
  deps: [OAuth2Client],
},

Now we have access to complete set of Google calendar API features with fully typed SDK interface.

You can get the calendar as you would any other Angular service, have it as a constructor parameter and dependency injection will provide it for you.

constructor(
  private calendar: calendar_v3.Calendar,
) {}

Here is an example of how to get a list of events of some specific calendar. We will also filter only events that are “today” and not deleted/cancelled.

this.calendar.events.list({
  // required, it is an email, or email like id of a calendar
  calendarId: CALENDAR_ID,
// optional, arguments that let you filter/specify wanted events
  timeMin: startOfDay(today).toISOString(),
  timeMax: endOfDay(today).toISOString(),
  showDeleted: false,
  singleEvents: true,
}),

You can also perform other tasks such as creating events but don’t forget to require proper scope claims in with your authentication.

Using the Analytics SDK

Setting permissions

⮕ Analytics Console ⮕ Admin ⮕ Account column ⮕ User Management ⮕
⮕ Select the user ⮕ Activate the "Read & Analyze" checkbox

Getting the “View ID”

⮕ Analytics Console ⮕ Admin ⮕ View column ⮕ View Settings ⮕
⮕ Copy the "View ID" number

Code Example

Same as in a previous example, you’ll need a provider. Provide Analytics class with the default auth method. Extend your app.module.ts providers array with this:

{
  provide: analytics_v3.Analytics,
  useFactory:
    (auth: OAuth2Client) => new analytics_v3.Analytics({ auth }),
  deps: [OAuth2Client],
},

Again you’ll have it ready to be injected by DI to any injectable class.

constructor(
  private analytics: analytics_v3.Analytics,
) {}

This example will get the specified metrics for the desired time range. In this case, we’ll see total page views for the last 30 days.

this.analytics.data.ga.get({
  ids: 'ga:xxxxxxxxx', // replace xxxxxxxxx with your view ID
  'start-date': '30daysAgo',
  'end-date': 'today',
  metrics: 'ga:pageviews',
})

Conclusion

Having a fully typed SDK for an API is a big difference compared to having to find it all in the docs especially the data models. The Auth part of the problem is also taken care of pretty conveniently so it is not a show stopper for people who don’t know how or don’t want to manage that.
Overall it is a lot easier to create features when you have the project environment and tools set up just right.

#angular #angularjs #programming

What is GEEK

Buddha Community

How to use Google's fully typed API SDK in Angular web application
Roberta  Ward

Roberta Ward

1595344320

Wondering how to upgrade your skills in the pandemic? Here's a simple way you can do it.

Corona Virus Pandemic has brought the world to a standstill.

Countries are on a major lockdown. Schools, colleges, theatres, gym, clubs, and all other public places are shut down, the country’s economy is suffering, human health is on stake, people are losing their jobs and nobody knows how worse it can get.

Since most of the places are on lockdown, and you are working from home or have enough time to nourish your skills, then you should use this time wisely! We always complain that we want some ‘time’ to learn and upgrade our knowledge but don’t get it due to our ‘busy schedules’. So, now is the time to make a ‘list of skills’ and learn and upgrade your skills at home!

And for the technology-loving people like us, Knoldus Techhub has already helped us a lot in doing it in a short span of time!

If you are still not aware of it, don’t worry as Georgia Byng has well said,

“No time is better than the present”

– Georgia Byng, a British children’s writer, illustrator, actress and film producer.

No matter if you are a developer (be it front-end or back-end) or a data scientisttester, or a DevOps person, or, a learner who has a keen interest in technology, Knoldus Techhub has brought it all for you under one common roof.

From technologies like Scala, spark, elastic-search to angular, go, machine learning, it has a total of 20 technologies with some recently added ones i.e. DAML, test automation, snowflake, and ionic.

How to upgrade your skills?

Every technology in Tech-hub has n number of templates. Once you click on any specific technology you’ll be able to see all the templates of that technology. Since these templates are downloadable, you need to provide your email to get the template downloadable link in your mail.

These templates helps you learn the practical implementation of a topic with so much of ease. Using these templates you can learn and kick-start your development in no time.

Apart from your learning, there are some out of the box templates, that can help provide the solution to your business problem that has all the basic dependencies/ implementations already plugged in. Tech hub names these templates as xlr8rs (pronounced as accelerators).

xlr8rs make your development real fast by just adding your core business logic to the template.

If you are looking for a template that’s not available, you can also request a template may be for learning or requesting for a solution to your business problem and tech-hub will connect with you to provide you the solution. Isn’t this helpful 🙂

Confused with which technology to start with?

To keep you updated, the Knoldus tech hub provides you with the information on the most trending technology and the most downloaded templates at present. This you’ll be informed and learn the one that’s most trending.

Since we believe:

“There’s always a scope of improvement“

If you still feel like it isn’t helping you in learning and development, you can provide your feedback in the feedback section in the bottom right corner of the website.

#ai #akka #akka-http #akka-streams #amazon ec2 #angular 6 #angular 9 #angular material #apache flink #apache kafka #apache spark #api testing #artificial intelligence #aws #aws services #big data and fast data #blockchain #css #daml #devops #elasticsearch #flink #functional programming #future #grpc #html #hybrid application development #ionic framework #java #java11 #kubernetes #lagom #microservices #ml # ai and data engineering #mlflow #mlops #mobile development #mongodb #non-blocking #nosql #play #play 2.4.x #play framework #python #react #reactive application #reactive architecture #reactive programming #rust #scala #scalatest #slick #software #spark #spring boot #sql #streaming #tech blogs #testing #user interface (ui) #web #web application #web designing #angular #coronavirus #daml #development #devops #elasticsearch #golang #ionic #java #kafka #knoldus #lagom #learn #machine learning #ml #pandemic #play framework #scala #skills #snowflake #spark streaming #techhub #technology #test automation #time management #upgrade

Top Enterprise Angular Web Apps Development Company in USA

AppClues Infotech is one of the leading Enterprise Angular Web Apps Development Company in USA. Our dedicated & highly experienced Angular app developers build top-grade Angular apps for your business with immersive technology & superior functionalities.

For more info:
Website: https://www.appcluesinfotech.com/
Email: info@appcluesinfotech.com
Call: +1-978-309-9910

#top enterprise angular web apps development company in usa #enterprise angular web apps development #hire enterprise angular web apps developers #best enterprise angular web app services #custom enterprise angular web apps solution #professional enterprise angular web apps developers

Sival Alethea

Sival Alethea

1624302000

APIs for Beginners - How to use an API (Full Course / Tutorial)

What is an API? Learn all about APIs (Application Programming Interfaces) in this full tutorial for beginners. You will learn what APIs do, why APIs exist, and the many benefits of APIs. APIs are used all the time in programming and web development so it is important to understand how to use them.

You will also get hands-on experience with a few popular web APIs. As long as you know the absolute basics of coding and the web, you’ll have no problem following along.
⭐️ Unit 1 - What is an API
⌨️ Video 1 - Welcome (0:00:00)
⌨️ Video 2 - Defining Interface (0:03:57)
⌨️ Video 3 - Defining API (0:07:51)
⌨️ Video 4 - Remote APIs (0:12:55)
⌨️ Video 5 - How the web works (0:17:04)
⌨️ Video 6 - RESTful API Constraint Scavenger Hunt (0:22:00)

⭐️ Unit 2 - Exploring APIs
⌨️ Video 1 - Exploring an API online (0:27:36)
⌨️ Video 2 - Using an API from the command line (0:44:30)
⌨️ Video 3 - Using Postman to explore APIs (0:53:56)
⌨️ Video 4 - Please please Mr. Postman (1:03:33)
⌨️ Video 5 - Using Helper Libraries (JavaScript) (1:14:41)
⌨️ Video 6 - Using Helper Libraries (Python) (1:24:40)

⭐️ Unit 3 - Using APIs
⌨️ Video 1 - Introducing the project (1:34:18)
⌨️ Video 2 - Flask app (1:36:07)
⌨️ Video 3 - Dealing with API Limits (1:50:00)
⌨️ Video 4 - JavaScript Single Page Application (1:54:27)
⌨️ Video 5 - Moar JavaScript and Recap (2:07:53)
⌨️ Video 6 - Review (2:18:03)
📺 The video in this post was made by freeCodeCamp.org
The origin of the article: https://www.youtube.com/watch?v=GZvSYJDk-us&list=PLWKjhJtqVAblfum5WiQblKPwIbqYXkDoC&index=5
🔥 If you’re a beginner. I believe the article below will be useful to you ☞ What You Should Know Before Investing in Cryptocurrency - For Beginner
⭐ ⭐ ⭐The project is of interest to the community. Join to Get free ‘GEEK coin’ (GEEKCASH coin)!
☞ **-----CLICK HERE-----**⭐ ⭐ ⭐
Thanks for visiting and watching! Please don’t forget to leave a like, comment and share!

#apis #apis for beginners #how to use an api #apis for beginners - how to use an api #application programming interfaces #learn all about apis

I am Developer

1610191977

Angular 11 Google Social Login Example

Angular 9/10/11 social login with google using angularx-social-login library example. In this tutorial, i will show you step by step on how to implement google social login in angular 11 app.

And also, this tutorial will show you How to login into Angular 10/11 application with google using angularx-social-login library in angular 11 app.

Google Login Integration In Angular 11 App

  • Step 1 - Create New Angular App
  • Step 2 - Install Social Login Library
  • Step 3 - Add Code on App.Module.ts File
  • Step 4 - Add Code on View File
  • Step 5 - Add Code On App.Component ts File
  • Step 6 - Start the Angular Google Login App

https://www.tutsmake.com/angular-11-google-social-login-example/

#angular 11 google login #angular 11 social-login example #login with google button angular 8/9/10/11 #angular 10/11 login with google #angular 10 social google login #angular social login google

I am Developer

1610191977

Angular 11 Google Social Login Example Tutorial

Angular 9/10/11 social login with google using angularx-social-login library example. In this tutorial, i will show you step by step on how to implement google social login in angular 11 app.

And also, this tutorial will show you How to login into Angular 10/11 application with google using angularx-social-login library in angular 11 app.

Google Login Integration In Angular 11 App

  • Step 1 - Create New Angular App
  • Step 2 - Install Social Login Library
  • Step 3 - Add Code on App.Module.ts File
  • Step 4 - Add Code on View File
  • Step 5 - Add Code On App.Component ts File
  • Step 6 - Start the Angular Google Login App

https://www.tutsmake.com/angular-11-google-social-login-example/

#angular 11 google login #angular 11 social-login example #login with google button angular 8/9/10/11 #angular 10/11 login with google #angular 10 social google login #angular social login google