Search code examples
pythongoogle-apigoogle-drive-apigoogle-api-python-client

python google api create folder with permission


i am trying to create a public folder in google drive and get in return a link for shareing this:

def createfolder(foldername,service):
    new_role='reader'
    types='anyone'
    # create folder
    file_metadata = {
        'name': '{}'.format(foldername),
        'mimeType': 'application/vnd.google-apps.folder',
         'role': 'reader',
         'type': 'anyone',

    }
    file = service.files().create(body=file_metadata,
                                  fields='id,webViewLink').execute()
    print('Folder ID: %s' % file.get('webViewLink'))
    return file.get('id')

i got this far
it creates and folder and prints the link
tryd to add the fields in to the body role and type and set it to reader / anyone but this not working
role type fields seem to be ignored
is there a way to do this on create or do i have to change the permission after i create it?


Solution

  • You have to call Permissions.create:

    File permissions are handled via Permissions, not through Files methods.

    If you check the Files resource representation, you'll notice that some fields, like name or mimeType, have the word writable under Notes. This means you can modify these fields directly using this resource (Files) methods.

    If you check the property permissions, though, you'll notice there's no writable there. This means permissions cannot be updated directly, using Files methods. You have to use Permissions methods instead.

    More specifically, you have to call Permissions.create after creating the folder and retrieving its ID.

    Code snippet:

    def shareWithEveryone(folderId, service):
        payload = {
            "role": "reader",
            "type": "anyone"
        }
        service.permissions().create(fileId=folderId, body=payload).execute()
    

    Reference: