Google Drive API: Playing around

Shivam Aggarwal
3 min readDec 13, 2018

--

This blog is about my experience working on Google Drive APIs while working on the current project. Although the documentation from Google is good, but I felt difficulties getting my way around it. Hence, I am consolidating my experience of using Google Drive APIs here. Throughout this example, we will use Python as our coding language.

Step 1: Setup Codebase

  1. Create Project repository
    cd ~/projects/google_drive_api
  2. If you do not have pip, install pip. Follow this link.
  3. Install virtual environment
    pip install — upgrade virtualenv
  4. Create virtual environment for our project. You can use any env_name for your project. For this example, we use google_apis.
    virtualenv <env_name>
  5. Activate this virtualenv
    source <env_name>/bin/activate
  6. Install google client api package for python
    pip install — upgrade google-api-python-client oauth2client

Step 2: Enable Google Drive API.

  1. Go to following link and hit ‘ENABLE THE DRIVE API’
    https://developers.google.com/drive/api/v3/quickstart/python
  2. Select your ongoing project or create a new project. Hit ‘next’.
  3. Choose a display name for your project. Hit ‘next’.
  4. Click ‘DOWNLOAD CLIENT CONFIGURATION’. It will download ‘credentials.json’ file.

Step 3: Create drive_client.py file

class DriveClient(object):
def connect(self):
creds_filename = <path/to/your/credentials.json>
store = file.Storage(creds_filename)
creds = store.get()
if not self.creds or self.creds.invalid:
scope = 'https://www.googleapis.com/auth/drive'
flow = client.flow_from_clientsecrets(creds_filename, scope)
creds = tools.run_flow(flow, store)
service = build('drive', 'v3', http=creds.authorize(Http()))

In the connect method in class DriveClient, we first try to locate the credentials.json file downloaded from Google when enabling Client APIs. Then, if store.get() method is able to extract authentication information, it will be assigned to creds variable. If it is not able to extract that information, it creates a flow with given credentials file and scope.

The purpose of Flow class is to acquire credentials data that authorize your application access data to user data. In general, to grant user access, the authorization process requires multiple redirections to the browser. Flow class helps with this process. Once credentials are produced, Flow object can be destroyed and is not needed further.
Scope defines the access to user data. To know more about which is suitable for use case, go to https://developers.google.com/drive/api/v3/about-auth. Once we have creds, we can build the service object specifying which Google service and its version.

Step 3.1: Create Request

def create(self, metadata):
file = service.files().create(body=metadata,
fields='id').execute()
return file.get('id')

Google Drive Service provides with very easy way of creating new files and folders. It just needs metadata about what file or folder to create, and fields to return. Metadata is a dictionary object containing information about file/folder to be created. To create a new folder, metadata will look like this —

metadata = { 
‘name’: <folder_name>,
‘mimeType’: ‘application/vnd.google-apps.folder’,
‘parents’: [<parent_folder_ids>]
}

folder_name field specify the name of the folder to be created. mimeType field suggests that the object to be created is of type ‘folder’. parents field takes a list of parent folder ids. This specifies all the folders when this new folder is created. If you have parents: [‘A’, ‘B’, ‘C’], and a new folder is ‘F’, it will create a new folder named ‘F’ in all ‘A’ , ‘B’ and ‘C’.

Step 3.2: Search Request

def search(self, query_str):
page_token = None
while True:
response = self._service.files().list(
q=query_str,
spaces='drive',
fields='nextPageToken, files(id, name)',
pageToken=page_token
).execute()

for file in response.get('files', []):
return file.get('id')

page_token = response.get('nextPageToken', None)

if page_token is None:
break

Search is a little trickier than rest. To search for a folder name or file name in Google Drive, we need to perform tree search. First, create a query string to search. For example,

query_str = '(mimeType = \'application/vnd.google-apps.folder\') and (name = \'{0}\')'.format(folder_name)

This query string will search for any entity with type as ‘folder’ and name as <folder_name>. For other search fields, refer here.
https://developers.google.com/drive/api/v3/search-parameters

Second, run this search query across each entity until you hit your first match. That’s what the above search method does. You can modify it to give all the search results. For every search through a new entity, we create a new page token called page_token. If it’s a match, we return the details from the match, else we retrieve the next page token and start search to the next entity.

Any suggestions or thoughts, let me know:
Insta + Twitter + LinkedIn + Medium | Shivam Aggarwal

--

--