How can I create a new folder with Google Drive API in Python?

google-drive-api, python

Solution

To create a folder on Drive, try:

    def createRemoteFolder(self, folderName, parentID = None):
        # Create a folder on Drive, returns the newely created folders ID
        body = {
          'title': folderName,
          'mimeType': "application/vnd.google-apps.folder"
        }
        if parentID:
            body['parents'] = [{'id': parentID}]
        root_folder = drive_service.files().insert(body = body).execute()
        return root_folder['id']

You only need a parent ID here if you want to create folder within another folder, otherwise just don't pass any value for that.

If you want the parent ID, you'll need to write a method to search Drive for folders with that parent name in that location (do a list() call) and then get the ID of that folder.

Edit: Note that v3 of the API uses a list for the 'parents' field, instead of a dictionary. Also, the `'title'` field changed to `'name'`, and the `insert()` method changed to `create()`. The code from above would change to the following for v3:

    def createRemoteFolder(self, folderName, parentID = None):
        # Create a folder on Drive, returns the newely created folders ID
        body = {
          'name': folderName,
          'mimeType': "application/vnd.google-apps.folder"
        }
        if parentID:
            body['parents'] = [parentID]
        root_folder = drive_service.files().create(body = body).execute()
        return root_folder['id']

Problem

From this example. Can I use MediafileUpload with creating folder? How can I get the parent_id from? From https://developers.google.com/drive/folder I just know that i should use mime = "application/vnd.google-apps.folder" but how do I implement this tutorial to programming in Python? Thank you for your suggestions.

Original source