Monday, December 2, 2013

Google Drive API - How to create a folder

Creating a file in Google Drive using the API is well documented:

https://developers.google.com/drive/v2/reference/files/insert

But, I can't find anywhere in that Google Drive SDK documentations a way to create a folder. After reading carefully the docs, I see that a folder is just a file in Google Drive. The different here is the mimeType. The mimeType of a folder is:

'application/vnd.google-apps.folder'

 
So, I wrote a function to create a folder in an authorized drive account, based on the docs example:


def create_a_folder(service, title, desc, parentid=None):
    body = {
        'title': title,
        'description': desc,
        'mimeType': 'application/vnd.google-apps.folder'
    }
    if parentid:
        body['parents'] = [{'id': parentid}]

    folder = service.files().insert(body=body).execute()
    pprint.pprint(folder)


    return folder['id']



"service" parameter is a drive service instance which can be retrieved by the following function:

def authorize_app(client_id, client_secrect, oauth_scope, redirect_uri):
    # Run through the OAuth flow and retrieve credentials
    flow = OAuth2WebServerFlow(client_id, client_secrect, oauth_scope, redirect_uri)
    authorize_url = flow.step1_get_authorize_url()
    print 'Go to the following link in your browser: ' + authorize_url
    code = raw_input('Enter verification code: ').strip()
    credentials = flow.step2_exchange(code)

    # Create an httplib2.Http object and authorize it with our credentials
    http = httplib2.Http()
    http = credentials.authorize(http)

    drive_service = build('drive', 'v2', http=http)


    return drive_service