Sunday, June 9, 2019

Google Drive API Javascript Example

On this tutorial, we gonna use Google Drive API for Javascript. We use NodeJS on this tutorial, so you must have NodeJS installed in your PC/Laptop.

For the API authentication, go to console.developers.google.com and choose your option. You can authenticate with API key, or by Oauth 2.0, and by Service Account. Your authentication is almost ready, you have to enable Google API you want to use, by visiting Google API Library https://console.developers.google.com/apis/library and enable Google Drive API.

Follow this step to use Google Drive API.


1. Share Files


To use the service account method of authentication, you’ll need to provide access to the service account. You can provide access on a file-by-file basis or at the level of folders. Find the "client_email" key in your credientials.json file and copy the value. This is the email address that you’ll need to share, and it will look something like:

service-account@projectname-123456.iam.gserviceaccount.com

Create a new folder in your account’s Google Drive, and then share it with the "client-email" in your credentials.json . Sharing access to the service account is required, and it’s one of the reasons a service account is more secure than a simple API key.


2. Install Google API packages


Open the terminal, making sure you’re in the project directory, and type npm i googleapis . The conventional way to import the module into a Node.js file is like this:

const { google } = require('googleapis');

3. Start Coding

Load the Google API library, read your credential.json files and use Google Drive scopes. We'll using Google Auth with JWT for this tutorial:

const { google } = require('googleapis');
const credentials = require('./credentials.json');
const scopes = [ 'https://www.googleapis.com/auth/drive' ];
const auth = new google.auth.JWT( credentials.client_email, null, credentials.private_key, scopes );

test your code with listing all files from your Drive account:

drive.files.list({}, (err, res) => {
if (err) throw err;
const files = res.data.files;
if (files.length) {
files.map((file) => {
console.log(file);
});
} else {
console.log('No files found');
}
});

0 comments:

Post a Comment