Noob’s guide to using any Google API in NodeJs
Published: 2022-06-18 07:15:22

Google offers multiple services to its users and also offers developers the option to build super cool stuff by integrating these services into their apps using their APIs. You can check the list of all the apis provided by Google [here](https://developers.google.com/apis-explorer)

In this article, I’ll walk you through the initial authentication step for using Google APIs. Lets jump right into it

## Creating a project in Google Cloud Console
To generate credentials for Google APIs, we need to create a project in Google Cloud Console. Sign in to Google Cloud Console with your google account and create a new project and follow the below steps:

### Step 1: Enabling Google API
In the sidemenu, select **APIs and Services** -> **Library** -> Search for the Google API you want to use and enable it

*Google offers two basic types of credentials to access their API -  API key and oAuth 2*

- *API key is used when accessing publicly available data like Google Maps*
- *oAuth 2 is used when accessing private data like a user’s Gmail account or Google drive*

Getting oAuth credentials involves setting up an oAuth consent screen. You can skip this step if you’re looking only for API Key authentication

### Step 2: Setting up the OAuth Screen
- Inside **APIs and Services** -> **OAuth Consent Screen** -> Select **User Type**. You can  **External** for testing
- On the next screen, enter all the application details
- In **Scopes** section, click on **Add Scopes**.  Each service offers different levels of permissions (i.e. scope) to client data. You can select the scope as per your project requirements.
- If your application is still in **Testing** phase and you selected **External** user type previous step, provide emails of all the users who can access your app
- Check the app summary and click **Save**

### Step 3: Generating Credentials
- **oAuth Client ID**
  - Again in **APIs and Services**, open **Credentials** -> **Create Credentials** -> **oAuth Client ID**
  - Select your **Application Type** and add
      - **Authorised Origin** - You can use localhost with port no. *http://localhost:3000* if your app is not hosted
      - **Callback URL** - This is the url where Google will send the response after OAuth. Again for locally hosted apps, you can use something like *http://localhost:3000/auth/google/callback*
- **API Key**
  - Generating API Key is fairly straight forward. Inside **APIs and Services**, select **Credentials** -> **Create Credentials** -> **API Key**

## Connecting our Node Project to Google API
For connecting to Google API, we’ll use the Node client library - **[googleapis](https://www.npmjs.com/package/googleapis).** Install it in your project using `npm i goolgeapis`

Now to store the cloud project credentials in your app, install [dotenv](https://www.npmjs.com/package/dotenv) and create a `.env` file

- For oAuth2 authentication, add `CLIENT_ID`, `CLIENT_SECRET` and `CALLBACK_URL` in the environment file.
- For API Key auth, just add the `API_KEY` and skip the next step

### Step 1: Creating an oAuth2 client
- In our app, we need to create a Node oAuth2 client using our generated credentials which validates our app as a valid client.

```
const { google } = require('googleapis');
require('dotenv').config();
const { CLIENT_ID, CLIENT_SECRET, CALLBACK_URL } = process.env;

const oauth2Client = new google.auth.OAuth2(
  CLIENT_ID,
  CLIENT_SECRET,
  CALLBACK_URL
);
```

- In order to authenticate the users of our app and get consent to access their data, we need to generate a unique url based on our project scope. So this allows our app to make requests to Google apis on behalf of the user.


```
//This method returns a url where the users can see the oAuth consent screen
function getGoogleAuthURL() {

  // Add all the scopes required by your app in this array. 
  // For example, if the scope needed by your app is /auth/calendar, 
  // add it as https://www.googleapis.com/auth/calendar in the array
  const scope = [
    'https://www.googleapis.com/<scope-that-you-selected-earlier>'
  ];

  return oauth2Client.generateAuthUrl({
	//'offline' mode will return a refresh token which we can save in our database to access the user's data in the future
    access_type: 'offline', 
    scope,
  });
}
``` 
- We can now create a separate route to redirect our users to the generated url

```
app.get('/auth/google', (req, res) => {
  res.redirect(getGoogleAuthURL());
});
```

- When the user is redirected to the callback route, we can get the user details and save it in our DB and perform any other operation as needed

```
async function getGoogleUser({ code }) {
  // This will return an object with the access_token and refresh_token
  const { tokens } = await oauth2Client.getToken(code);
  oauth2Client.setCredentials({
    refresh_token: tokens.refresh_token
  });

  // Fetch the user's profile with the access token and bearer
  const googleUser = await axios
    .get(
      `https://www.googleapis.com/oauth2/v1/userinfo?alt=json&access_token=${tokens.access_token}`,
      {
        headers: {
          Authorization: `Bearer ${tokens.id_token}`,
        },
      },
    )
    .then(res => {
      return { data: res.data, refresh_token: tokens.refresh_token };
    })
    .catch(error => {
      throw new Error(error.message);
    });
    return googleUser;
}

app.get('/auth/google/callback', async (req, res) => {
  try {
    const googleUser = await getGoogleUser(req.query);
  
	//Get user id, email and name from the response
    const { id, email, name } = googleUser.data;

	//You can store this refresh token in your db for future access
	const refreshToken = googleUser.refresh_token;

	//Store the data in DB and redirect to some other page

  } catch(err) {
    //Error handling logic here
  }
})
``` 
### Step 2: Authenticating API requests

- We can authenticate all of our requests either at the global level or at a service level to avoid dealing with it in every request we send
- For API Key authentication, just replace the `oauth2Client` with `API_KEY`

```
// Global authentication
google.options({
  auth: oauth2Client
});

// Service level authentication - Example with Google Drive service
const drive = google.drive({
  version: 'v2',
  auth: oauth2Client
});
```

And voila! Our Node app is now authenticated to use Google APIs. You can now easily GET and POST data to any of the Google apis provided you have defined the right scope.
![Dance](https://media.giphy.com/media/fA81FF4mdE6lgeoJwb/giphy.gif)

You can checkout endpoints for any of api in [Google Api explorer](https://developers.google.com/apis-explorer) and refer the googleapis documentation [here](https://googleapis.dev/nodejs/googleapis/latest/index.html)

Thank you! Do let me know in the comments if you have any questions.

Stay healthy, Stay happy, Stay safe. Cheers!