Site icon Mobile App Development Services

Integration of Google drive API with React Native

React native has been one of the successful Mobile app framework that allows to create applications for Android, Android TV, iOS, macOS, tvOS, Web, Windows and UWP developed on Javascript. With the pace of time, many new cross-platform mobile development tools have been introduced. Despite this all, React Native has still been one of the top choices.

In this era, where Google has covered almost every device. The need of authentication has been clearly reduced to just a Google sign-in. Mostly, the users prefer to use a single account for login, thanks to Google. While, other popular services provided by Google like Google Drive is quite handy too.

In this blog, you’ll learn how to integrate the Google Drive API with React Native and cover basic operations enough for storing your content, or creating Backups. The steps mentioned below will cover the following,

  1. Creating a folder on Google Drive
  2. Creating a file in that folder
  3. Listing the uploaded files
  4. Accessing the contents.

We will be using the Google Drive API Wrapper for React Native, which is react-native-google-drive-api-wrapper.

It is assumed that you have already integrated the Google Sign-In API with your app. If not, follow the steps mentioned in react-native-google-signin, integrate it and get the web client Id.

Step#1: Installing the Google Drive API Wrapper

Follow the simple guide and install the wrapper. Don’t forget to install the react-native-fs too. Once installed, make sure everything is linked and configured properly.

Step#2: Configure the Google Sign-in

You must have web client id obtained from Google Developers Console in your credentials tab for the project created. Then use the code given below.

import {GoogleSignin, statusCodes} from 'react-native-google-signin';
	import GDrive from 'react-native-google-drive-api-wrapper';

//In your useEffect / componentDidMount function	
  GoogleSignin.configure({
		scopes: // Will be covered in Step 4
webClientId:'xyz0yxa-xyzxyzxyznlpsi.apps.googleusercontent.com', 
offlineAccess: true,
});

Step#3: Setup User Sign-in, obtain the Access Token and Initialize the GDrive API

Setup the code for User sign-in through react-native-google-signin. Once signed in, you can obtain the access token and set the obtained token for GDrive API and initialize it.

signIn = async () => {
    	try {
      		await GoogleSignin.hasPlayServices();
      		const userInfo = await GoogleSignin.signIn();
     		const token = (await GoogleSignin.getTokens()).accessToken;
		//Save the Token and User Info
		//To get the user email, userInfo.user.email

// Set the token for Gdrive
GDrive.setAccessToken(this.state.accToken);  
GDrive.init(); // Initialize the GDrive

	//You can extract the error types from statusCodes as follows.

  	} catch (error) {
      	if (error.code === statusCodes.SIGN_IN_CANCELLED) {
        			// user cancelled the login flow
      	} else if (error.code === statusCodes.IN_PROGRESS) {
       			// operation (f.e. sign in) is in progress already
      	} else if (error.code === statusCodes.PLAY_SERVICES_NOT_AVAILABLE) {
// play services not available or outdated
      	} else {
        			// some other error happened
}
    	}};

Step#4: Understanding and Setting Scopes

In order to perform operations like (listing, creating folders, uploading files, etc.) we’ve to understand the specific scopes required. Scopes represent the access you need from the user. Sensitive scopes might require you to verify your App. You can check the recommended, sensitive and restricted scopes for Google Drive API here.

Our use case here is simply to create a file in a folder, get the list of files in a folder, and get contents of a file (An enough approach for Backing up the data on Google Drive).

So, for that we will be using the scopes given below,

GoogleSignin.configure({
		scopes: [
        		'https://www.googleapis.com/auth/drive.appdata',
        		'https://www.googleapis.com/auth/drive.file',
      		], // what API you want to access on behalf of the user, default is
   // email and profile
webClientId:'xyz0yxa-xyzxyzxyznlpsi.apps.googleusercontent.com', 
offlineAccess: true,
});

Step#5: Creating a Folder

Once the GDrive is initialised, we can create a folder of our concern, i.e. My Diaries/ My Backups, or whatever your use case is.
The method safeCreateFolder will create a folder if it doesn’t exist, or returns the folderId if it exists. The FolderId is required to access the contents of folder.

if (GDrive.isInitialized()) {
//Google Drive is Initialized Now!!
        		try {
          		  const folderId = await GDrive.files.safeCreateFolder({
            		  name: 'My Backups',
          		  parents: ['root'],
          		}); 
} catch(err) {
   //.. catch the error accordingly
} }

Step#6: Creating a file

To create a text file in the same folder, get the folderId of that folder and create the file in it. We’ll be using the createFileMultipart method to achieve this.

let content=”My first text file on GDrive”
	const folderId = await GDrive.files.safeCreateFolder({
        		name: 'My Backups',
       		 parents: ['root'],
      		});
	//Now to upload it
	//Put the folderId as parent for creating the file
	GDrive.files.createFileMultipart(
          		content,
          		'text/plain',
         		 {
            			parents: [folderId],
            			name: 'Backup1'.txt',
          		},
          		false,
        		)
    .then(response => {
 		//DONE
}).catch(er => {
    //… catch the error accordingly
});

Step#7: Listing the files

To list the files in any folder, obtain the folderId of that folder and use the below code.

GDrive.files.list({
       q: "'" + folderId + "' in parents",
})
.then(res => res.json())
.then(data => {
	// access the files name like data.files[1].name
	// data.files is the array having the list of files
})
.catch(err => {
       //… catch the error accordingly
});

Step#8: Access the contents of File

To access the data in the file, simply get the id of the file by data.files[0].id, and access the contents through that id.

GDrive.files.get(id, {alt: 'media'})
.then(res => { //access the data in res}
.catch(err=> { //… catch the error accordingly }

All the methods used in the above steps are listed in react-native-google-drive-api-wrapper. If you want to use other methods, go through the documentation.

So, in this way you can integrate the Google Drive API with React native and store your files. There can be variety of use cases that can be achieved through Google Drive, whether that is backup of your local data which you want to store or setting up the whole mechanism of JSON based import/export of files. Thanks for reading,
Don’t forget to give a thumbs up!