Hi, In this blog post we learn about, how to use google drive API in javascript on the web. Using this API we will upload, download, update and delete files from google drive using API in javascript.

Create Project on Google Cloud

Before we start coding, we need to create a project on google cloud. Open cloud console, and click on the dropdown button on the top to select a project. A popup will open. Then click "New Project" on the right side of the popup. Then give project name and click "Create". After that, your project dashboard will open and then click on "Go to APIs overview". A new window will open with some nav menus on the left side.

OAuth consent screen

Click on "OAuth consent screen" menu then consent screen of your project will open. Make sure, your project is selected on the top dropdown. Click on "External" and then click create. Provide some information about your new app like "App Name", "App Logo" and email for developer contact. After all, click "Save And Continue" to go to the "Scopes" tab.

You can skip scopes to continue without verification. But, if you want to verify your app in google, then must select a scope. Scope for google drive is "https://www.googleapis.com/auth/drive". This will help in getting permissions for your verified app to read/write in the user's google drive. It's a sensitive scope and google developer team takes more time than usual to verify your app. You will also get an email asking to provide some video documentation on how users are using your app. But if you don't want to verify your app then you don't need any scope. It will work perfectly but look unprofessional.

Then go to the "Test users" tab. Nothing needs to provide here. Go to the "Summary" tab. Preview your info there. After that, click "Back To Dashboard".

Credentials

Click on "Credentials" menu to create API key and Client ID for your project. On new window, click on "Create Credentials", and click "OAuth client ID" on the popup box. Then select "Application Type" as "Web application" from the dropdown and then name your client ID. After that, set "JavaScrip Origins" which is URL used by your app. You can add multiple origins and can also add localhost as origin. After that, click create.

Now again click on "Create Credentials" and this time click on "API key" on the popup box. Your API key will be generated automatically and project is ready to use now.

Add CDNs In HTML File

Before start using drive API, add two CDNs, one for google drive API and another one for handling user's sign-in to their google drive with proper authentication.

Create Connection with Cloud Project

Now link your javascript project to the cloud project created before. Copy your project Client ID and API key from the cloud project and store them in variables. Also, add discovery docs and scopes, that are the same for each google drive project. Add two buttons for sign-in and sign-out that are initially hidden.

Handel Sign-in & Out

According to google drive API documentation, run two functions gapiLoaded() and gisLoaded() on window load. GapiLoaded() will initialize drive API using API key and discovery docs. GisLoaded() will load Google Identity Services using Client Id and Scopes. When both services are loaded into the project, then show the sign-in button to the user using maybeEnableButtons().

Now, run handleAuthClick(), when user click on sign-in button. This function will request for access token by showing a popup where the user enters email and password and accept some permissions to let the app use their google drive. If user sign-in is successful, then google granted access token with full permissions to the app for that session. Now app can do changes to user's google drive. Also, show the sign-out button on the callback.

And, when user click on the sign-out button, run handleSignoutClick(). This will revoke the access token. Show the sign-in button on callback.

Check a Folder

List functions are used to get the complete list of files, according to drive documentation. But, we can filter data using some parameters to get desired data. Here, we will use this function to check a specific folder by giving the name of the folder as given below. If response.result.files > 0 then folder available and return an object with four keys (id, kind, mimeType, name).

Create a Folder

For creating a folder, we need access_token, which was granted by google on sign-in. Now, use the request function with proper path as given below as parameter along with the POST method and headers. Give the folder name in the body with mimeType. On execute function, it will return an id as a response, which you can use further.

Upload a File

For uploading a file in google drive, provide some file metadata like filename, mimeType and parent folder id as an object and append object as JSON Blob in FormData() using key name "metadata". Then provide file as blob and append it in same FormData() using key name "file" and provide FormData() to the body. Also set the method and headers as given below. After that, this function will create a file in given parent folder with given file name.

Get Files List Using Parent Folder

This is same function as that used in checking a folder. Just need to change query to 'q': `parents in "${parent_Folder_id}"`. Provide the parent folder id to get the list from a specific folder. This will get 100 files as response in one request. All the files have id's and file name in their response. You can remove query to get the files list from the whole drive.

Download a File

Use the google drive get function to get the files as response and then convert response to blobs and then to object URL. Give the type in creating blob carefully according to your file type. Also give a download file name with proper extension like for text file it is some-file-name.txt and for image file it is some-file-name.png.

Update a File

Update function is similar to the upload function but just one thing that we are not able to change meta information of the file. Only files can be replaced using given id. If you are updating a text file just provide new text to body. It will automatically be updated in file. But, if you updating a video or image file then provide a blob.

Delete a File

Delete is a simple function, we just need to provide file id and execute delete function then that file will be deleted from google drive.

Final Thoughts

Google Drive is one of the best free cloud-based storage services and learning the API of such an application will definitely be fruitful. You can create your own google drive application and learn about APIs. I tried to elaborate on each and every step, but still, if you have any issues, then comment below. Get the source code below, to get more help.

Reference from Google Drive API documentation