How to create a shared google docs folder

Some common Google Drive files include Docs, Sheets, Slides, Forms and Drawings. To display any of these on your site, they must be public, however you can choose if you want to allow visitors to edit and comment as well.

Every Google Drive file, folder, and shared drive have associated Permissions resources. Each resource identifies the permission for a specific type (user, group, domain, anyone) and role, such as "commenter" or "reader." For example, a file might have a permission granting a specific user (type=user) read-only access (role=reader) while another permission grants members of a specific group (type=group) the ability to add comments to a file (

from __future__ import print_function

import google.auth
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError


def share_file(real_file_id, real_user, real_domain):
    """Batch permission modification.
    Args:
        real_file_id: file Id
        real_user: User ID
        real_domain: Domain of the user ID
    Prints modified permissions

    Load pre-authorized user credentials from the environment.
    TODO(developer) - See https://developers.google.com/identity
    for guides on implementing OAuth2 for the application.
    """
    creds, _ = google.auth.default()

    try:
        # create drive api client
        service = build('drive', 'v3', credentials=creds)
        ids = []
        file_id = real_file_id

        def callback(request_id, response, exception):
            if exception:
                # Handle error
                print(exception)
            else:
                print(f'Request_Id: {request_id}')
                print(F'Permission Id: {response.get("id")}')
                ids.append(response.get('id'))

        # pylint: disable=maybe-no-member
        batch = service.new_batch_http_request(callback=callback)
        user_permission = {
            'type': 'user',
            'role': 'writer',
            'emailAddress': '[email protected]'
        }
        batch.add(service.permissions().create(fileId=file_id,
                                               body=user_permission,
                                               fields='id',))
        domain_permission = {
            'type': 'domain',
            'role': 'reader',
            'domain': 'example.com'
        }
        domain_permission['domain'] = real_domain
        batch.add(service.permissions().create(fileId=file_id,
                                               body=domain_permission,
                                               fields='id',))
        batch.execute()

    except HttpError as error:
        print(F'An error occurred: {error}')
        ids = None

    return ids


if __name__ == '__main__':
    share_file(real_file_id='1dUiRSoAQKkM3a4nTPeNQWgiuau1KdQ_l',
               real_user='[email protected]',
               real_domain='workspacesamples.dev')
0).

For a complete list of roles and the operations permitted by each, refer to Roles.

Note: The list of all permission resources associated with a file, folder, or shared drive, is known as an Access Control List (ACL).

Scenarios for sharing Drive resources

There are 5 different types of sharing scenarios:

  1. To share a file in My Drive, the user must have the role of "writer" or higher.

    • If the

      from __future__ import print_function
      
      import google.auth
      from googleapiclient.discovery import build
      from googleapiclient.errors import HttpError
      
      
      def share_file(real_file_id, real_user, real_domain):
          """Batch permission modification.
          Args:
              real_file_id: file Id
              real_user: User ID
              real_domain: Domain of the user ID
          Prints modified permissions
      
          Load pre-authorized user credentials from the environment.
          TODO(developer) - See https://developers.google.com/identity
          for guides on implementing OAuth2 for the application.
          """
          creds, _ = google.auth.default()
      
          try:
              # create drive api client
              service = build('drive', 'v3', credentials=creds)
              ids = []
              file_id = real_file_id
      
              def callback(request_id, response, exception):
                  if exception:
                      # Handle error
                      print(exception)
                  else:
                      print(f'Request_Id: {request_id}')
                      print(F'Permission Id: {response.get("id")}')
                      ids.append(response.get('id'))
      
              # pylint: disable=maybe-no-member
              batch = service.new_batch_http_request(callback=callback)
              user_permission = {
                  'type': 'user',
                  'role': 'writer',
                  'emailAddress': '[email protected]'
              }
              batch.add(service.permissions().create(fileId=file_id,
                                                     body=user_permission,
                                                     fields='id',))
              domain_permission = {
                  'type': 'domain',
                  'role': 'reader',
                  'domain': 'example.com'
              }
              domain_permission['domain'] = real_domain
              batch.add(service.permissions().create(fileId=file_id,
                                                     body=domain_permission,
                                                     fields='id',))
              batch.execute()
      
          except HttpError as error:
              print(F'An error occurred: {error}')
              ids = None
      
          return ids
      
      
      if __name__ == '__main__':
          share_file(real_file_id='1dUiRSoAQKkM3a4nTPeNQWgiuau1KdQ_l',
                     real_user='[email protected]',
                     real_domain='workspacesamples.dev')
      1 boolean value is set to
      from __future__ import print_function
      
      import google.auth
      from googleapiclient.discovery import build
      from googleapiclient.errors import HttpError
      
      
      def share_file(real_file_id, real_user, real_domain):
          """Batch permission modification.
          Args:
              real_file_id: file Id
              real_user: User ID
              real_domain: Domain of the user ID
          Prints modified permissions
      
          Load pre-authorized user credentials from the environment.
          TODO(developer) - See https://developers.google.com/identity
          for guides on implementing OAuth2 for the application.
          """
          creds, _ = google.auth.default()
      
          try:
              # create drive api client
              service = build('drive', 'v3', credentials=creds)
              ids = []
              file_id = real_file_id
      
              def callback(request_id, response, exception):
                  if exception:
                      # Handle error
                      print(exception)
                  else:
                      print(f'Request_Id: {request_id}')
                      print(F'Permission Id: {response.get("id")}')
                      ids.append(response.get('id'))
      
              # pylint: disable=maybe-no-member
              batch = service.new_batch_http_request(callback=callback)
              user_permission = {
                  'type': 'user',
                  'role': 'writer',
                  'emailAddress': '[email protected]'
              }
              batch.add(service.permissions().create(fileId=file_id,
                                                     body=user_permission,
                                                     fields='id',))
              domain_permission = {
                  'type': 'domain',
                  'role': 'reader',
                  'domain': 'example.com'
              }
              domain_permission['domain'] = real_domain
              batch.add(service.permissions().create(fileId=file_id,
                                                     body=domain_permission,
                                                     fields='id',))
              batch.execute()
      
          except HttpError as error:
              print(F'An error occurred: {error}')
              ids = None
      
          return ids
      
      
      if __name__ == '__main__':
          share_file(real_file_id='1dUiRSoAQKkM3a4nTPeNQWgiuau1KdQ_l',
                     real_user='[email protected]',
                     real_domain='workspacesamples.dev')
      2 for the file, the user must have the "owner" role.

    • If the user with the role of "writer" has temporary access governed by an expiration date and time, they can't share the file.

    For more information, see Add an expiration date.

  2. To share a folder in My Drive, the user must have the role of "writer" or higher.

    • If the

      from __future__ import print_function
      
      import google.auth
      from googleapiclient.discovery import build
      from googleapiclient.errors import HttpError
      
      
      def share_file(real_file_id, real_user, real_domain):
          """Batch permission modification.
          Args:
              real_file_id: file Id
              real_user: User ID
              real_domain: Domain of the user ID
          Prints modified permissions
      
          Load pre-authorized user credentials from the environment.
          TODO(developer) - See https://developers.google.com/identity
          for guides on implementing OAuth2 for the application.
          """
          creds, _ = google.auth.default()
      
          try:
              # create drive api client
              service = build('drive', 'v3', credentials=creds)
              ids = []
              file_id = real_file_id
      
              def callback(request_id, response, exception):
                  if exception:
                      # Handle error
                      print(exception)
                  else:
                      print(f'Request_Id: {request_id}')
                      print(F'Permission Id: {response.get("id")}')
                      ids.append(response.get('id'))
      
              # pylint: disable=maybe-no-member
              batch = service.new_batch_http_request(callback=callback)
              user_permission = {
                  'type': 'user',
                  'role': 'writer',
                  'emailAddress': '[email protected]'
              }
              batch.add(service.permissions().create(fileId=file_id,
                                                     body=user_permission,
                                                     fields='id',))
              domain_permission = {
                  'type': 'domain',
                  'role': 'reader',
                  'domain': 'example.com'
              }
              domain_permission['domain'] = real_domain
              batch.add(service.permissions().create(fileId=file_id,
                                                     body=domain_permission,
                                                     fields='id',))
              batch.execute()
      
          except HttpError as error:
              print(F'An error occurred: {error}')
              ids = None
      
          return ids
      
      
      if __name__ == '__main__':
          share_file(real_file_id='1dUiRSoAQKkM3a4nTPeNQWgiuau1KdQ_l',
                     real_user='[email protected]',
                     real_domain='workspacesamples.dev')
      1boolean value is set to
      from __future__ import print_function
      
      import google.auth
      from googleapiclient.discovery import build
      from googleapiclient.errors import HttpError
      
      
      def share_file(real_file_id, real_user, real_domain):
          """Batch permission modification.
          Args:
              real_file_id: file Id
              real_user: User ID
              real_domain: Domain of the user ID
          Prints modified permissions
      
          Load pre-authorized user credentials from the environment.
          TODO(developer) - See https://developers.google.com/identity
          for guides on implementing OAuth2 for the application.
          """
          creds, _ = google.auth.default()
      
          try:
              # create drive api client
              service = build('drive', 'v3', credentials=creds)
              ids = []
              file_id = real_file_id
      
              def callback(request_id, response, exception):
                  if exception:
                      # Handle error
                      print(exception)
                  else:
                      print(f'Request_Id: {request_id}')
                      print(F'Permission Id: {response.get("id")}')
                      ids.append(response.get('id'))
      
              # pylint: disable=maybe-no-member
              batch = service.new_batch_http_request(callback=callback)
              user_permission = {
                  'type': 'user',
                  'role': 'writer',
                  'emailAddress': '[email protected]'
              }
              batch.add(service.permissions().create(fileId=file_id,
                                                     body=user_permission,
                                                     fields='id',))
              domain_permission = {
                  'type': 'domain',
                  'role': 'reader',
                  'domain': 'example.com'
              }
              domain_permission['domain'] = real_domain
              batch.add(service.permissions().create(fileId=file_id,
                                                     body=domain_permission,
                                                     fields='id',))
              batch.execute()
      
          except HttpError as error:
              print(F'An error occurred: {error}')
              ids = None
      
          return ids
      
      
      if __name__ == '__main__':
          share_file(real_file_id='1dUiRSoAQKkM3a4nTPeNQWgiuau1KdQ_l',
                     real_user='[email protected]',
                     real_domain='workspacesamples.dev')
      2 for the file, the user must have the more permissive role of "owner".

    • Temporary access (governed by an expiration date and time) isn't allowed on My Drive folders with the role of "writer".

  3. To share a file in a shared drive, the user must have the role of "writer" or higher.

    • The

      from __future__ import print_function
      
      import google.auth
      from googleapiclient.discovery import build
      from googleapiclient.errors import HttpError
      
      
      def share_file(real_file_id, real_user, real_domain):
          """Batch permission modification.
          Args:
              real_file_id: file Id
              real_user: User ID
              real_domain: Domain of the user ID
          Prints modified permissions
      
          Load pre-authorized user credentials from the environment.
          TODO(developer) - See https://developers.google.com/identity
          for guides on implementing OAuth2 for the application.
          """
          creds, _ = google.auth.default()
      
          try:
              # create drive api client
              service = build('drive', 'v3', credentials=creds)
              ids = []
              file_id = real_file_id
      
              def callback(request_id, response, exception):
                  if exception:
                      # Handle error
                      print(exception)
                  else:
                      print(f'Request_Id: {request_id}')
                      print(F'Permission Id: {response.get("id")}')
                      ids.append(response.get('id'))
      
              # pylint: disable=maybe-no-member
              batch = service.new_batch_http_request(callback=callback)
              user_permission = {
                  'type': 'user',
                  'role': 'writer',
                  'emailAddress': '[email protected]'
              }
              batch.add(service.permissions().create(fileId=file_id,
                                                     body=user_permission,
                                                     fields='id',))
              domain_permission = {
                  'type': 'domain',
                  'role': 'reader',
                  'domain': 'example.com'
              }
              domain_permission['domain'] = real_domain
              batch.add(service.permissions().create(fileId=file_id,
                                                     body=domain_permission,
                                                     fields='id',))
              batch.execute()
      
          except HttpError as error:
              print(F'An error occurred: {error}')
              ids = None
      
          return ids
      
      
      if __name__ == '__main__':
          share_file(real_file_id='1dUiRSoAQKkM3a4nTPeNQWgiuau1KdQ_l',
                     real_user='[email protected]',
                     real_domain='workspacesamples.dev')
      1 setting doesn't apply to items in shared drives. It's treated as if it's always set to
      from __future__ import print_function
      
      import google.auth
      from googleapiclient.discovery import build
      from googleapiclient.errors import HttpError
      
      
      def share_file(real_file_id, real_user, real_domain):
          """Batch permission modification.
          Args:
              real_file_id: file Id
              real_user: User ID
              real_domain: Domain of the user ID
          Prints modified permissions
      
          Load pre-authorized user credentials from the environment.
          TODO(developer) - See https://developers.google.com/identity
          for guides on implementing OAuth2 for the application.
          """
          creds, _ = google.auth.default()
      
          try:
              # create drive api client
              service = build('drive', 'v3', credentials=creds)
              ids = []
              file_id = real_file_id
      
              def callback(request_id, response, exception):
                  if exception:
                      # Handle error
                      print(exception)
                  else:
                      print(f'Request_Id: {request_id}')
                      print(F'Permission Id: {response.get("id")}')
                      ids.append(response.get('id'))
      
              # pylint: disable=maybe-no-member
              batch = service.new_batch_http_request(callback=callback)
              user_permission = {
                  'type': 'user',
                  'role': 'writer',
                  'emailAddress': '[email protected]'
              }
              batch.add(service.permissions().create(fileId=file_id,
                                                     body=user_permission,
                                                     fields='id',))
              domain_permission = {
                  'type': 'domain',
                  'role': 'reader',
                  'domain': 'example.com'
              }
              domain_permission['domain'] = real_domain
              batch.add(service.permissions().create(fileId=file_id,
                                                     body=domain_permission,
                                                     fields='id',))
              batch.execute()
      
          except HttpError as error:
              print(F'An error occurred: {error}')
              ids = None
      
          return ids
      
      
      if __name__ == '__main__':
          share_file(real_file_id='1dUiRSoAQKkM3a4nTPeNQWgiuau1KdQ_l',
                     real_user='[email protected]',
                     real_domain='workspacesamples.dev')
      6.

    • Temporary access (governed by an expiration date and time) isn't allowed in shared drives.

  4. To share a folder in a shared drive, the user must have the role of "organizer."

  5. To manage shared drive membership, the user must have the role of "organizer." Only users and groups can be members of shared drives.

Permission propagation

Permission lists for a folder propagate downward, and all child files and folders inherit permissions from the parent. Whenever permissions or the hierarchy is changed, the propagation occurs recursively through all nested folders. For example, if a file exists in a folder and that folder is then moved within another folder, the permissions on the new folder propagates to the file. If the new folder grants the user of the file a new role, such as "writer," it overrides their old role.

Conversely, if a file inherits the "writer" role from a folder, and is moved to another folder that provides a "reader" role, the file now inherits the "reader" role.

Inherited permissions can't be removed from a file or folder in a shared drive. Instead these permissions must be adjusted on the direct or indirect parent from which they were inherited. Inherited permissions can be removed from items under "My Drive" or "Shared with me."

Conversely, inherited permissions can be overridden on a file or folder in My Drive. So, if a file inherits the role of "writer" from a My Drive folder, you can set the role of "reader" on the file to lower its permission level.

Warning: In "My Drive" and "Shared with me," propagation might stop if a different user owns the child file or folder and the file or folder has more restrictive permissions that override the propagation. For example, a parent folder might have type=group and
from __future__ import print_function

import google.auth
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError


def share_file(real_file_id, real_user, real_domain):
    """Batch permission modification.
    Args:
        real_file_id: file Id
        real_user: User ID
        real_domain: Domain of the user ID
    Prints modified permissions

    Load pre-authorized user credentials from the environment.
    TODO(developer) - See https://developers.google.com/identity
    for guides on implementing OAuth2 for the application.
    """
    creds, _ = google.auth.default()

    try:
        # create drive api client
        service = build('drive', 'v3', credentials=creds)
        ids = []
        file_id = real_file_id

        def callback(request_id, response, exception):
            if exception:
                # Handle error
                print(exception)
            else:
                print(f'Request_Id: {request_id}')
                print(F'Permission Id: {response.get("id")}')
                ids.append(response.get('id'))

        # pylint: disable=maybe-no-member
        batch = service.new_batch_http_request(callback=callback)
        user_permission = {
            'type': 'user',
            'role': 'writer',
            'emailAddress': '[email protected]'
        }
        batch.add(service.permissions().create(fileId=file_id,
                                               body=user_permission,
                                               fields='id',))
        domain_permission = {
            'type': 'domain',
            'role': 'reader',
            'domain': 'example.com'
        }
        domain_permission['domain'] = real_domain
        batch.add(service.permissions().create(fileId=file_id,
                                               body=domain_permission,
                                               fields='id',))
        batch.execute()

    except HttpError as error:
        print(F'An error occurred: {error}')
        ids = None

    return ids


if __name__ == '__main__':
    share_file(real_file_id='1dUiRSoAQKkM3a4nTPeNQWgiuau1KdQ_l',
               real_user='[email protected]',
               real_domain='workspacesamples.dev')
0, but a child folder has type=group (with the same email) and role=reader. Since
/**
 * Batch permission modification
 * @param{string} fileId file ID
 * @param{string} targetUserEmail username
 * @param{string} targetDomainName domain
 * @return{list} permission id
 * */
async function shareFile(fileId, targetUserEmail, targetDomainName) {
  const {GoogleAuth} = require('google-auth-library');
  const {google} = require('googleapis');

  // Get credentials and build service
  // TODO (developer) - Use appropriate auth mechanism for your app
  const auth = new GoogleAuth({
    scopes: 'https://www.googleapis.com/auth/drive',
  });
  const service = google.drive({version: 'v3', auth});
  const permissionIds = [];

  const permissions = [
    {
      type: 'user',
      role: 'writer',
      emailAddress: targetUserEmail, // '[email protected]',
    },
    {
      type: 'domain',
      role: 'writer',
      domain: targetDomainName, // 'example.com',
    },
  ];
  // Note: Client library does not currently support HTTP batch
  // requests. When possible, use batched requests when inserting
  // multiple permissions on the same item. For this sample,
  // permissions are inserted serially.
  for (const permission of permissions) {
    try {
      const result = await service.permissions.create({
        resource: permission,
        fileId: fileId,
        fields: 'id',
      });
      permissionIds.push(result.data.id);
      console.log(`Inserted permission id: ${result.data.id}`);
    } catch (err) {
      // TODO(developer): Handle failed permissions
      console.error(err);
    }
  }
  return permissionIds;
}
1 is more restrictive than
/**
 * Batch permission modification
 * @param{string} fileId file ID
 * @param{string} targetUserEmail username
 * @param{string} targetDomainName domain
 * @return{list} permission id
 * */
async function shareFile(fileId, targetUserEmail, targetDomainName) {
  const {GoogleAuth} = require('google-auth-library');
  const {google} = require('googleapis');

  // Get credentials and build service
  // TODO (developer) - Use appropriate auth mechanism for your app
  const auth = new GoogleAuth({
    scopes: 'https://www.googleapis.com/auth/drive',
  });
  const service = google.drive({version: 'v3', auth});
  const permissionIds = [];

  const permissions = [
    {
      type: 'user',
      role: 'writer',
      emailAddress: targetUserEmail, // '[email protected]',
    },
    {
      type: 'domain',
      role: 'writer',
      domain: targetDomainName, // 'example.com',
    },
  ];
  // Note: Client library does not currently support HTTP batch
  // requests. When possible, use batched requests when inserting
  // multiple permissions on the same item. For this sample,
  // permissions are inserted serially.
  for (const permission of permissions) {
    try {
      const result = await service.permissions.create({
        resource: permission,
        fileId: fileId,
        fields: 'id',
      });
      permissionIds.push(result.data.id);
      console.log(`Inserted permission id: ${result.data.id}`);
    } catch (err) {
      // TODO(developer): Handle failed permissions
      console.error(err);
    }
  }
  return permissionIds;
}
2, the child folder's permission overrides propagation from the parent folder.

Capabilities

The Permissions resource doesn't ultimately determine the current user's ability to perform actions on a file or folder. Instead, a Files resource contains a collection of boolean

/**
 * Batch permission modification
 * @param{string} fileId file ID
 * @param{string} targetUserEmail username
 * @param{string} targetDomainName domain
 * @return{list} permission id
 * */
async function shareFile(fileId, targetUserEmail, targetDomainName) {
  const {GoogleAuth} = require('google-auth-library');
  const {google} = require('googleapis');

  // Get credentials and build service
  // TODO (developer) - Use appropriate auth mechanism for your app
  const auth = new GoogleAuth({
    scopes: 'https://www.googleapis.com/auth/drive',
  });
  const service = google.drive({version: 'v3', auth});
  const permissionIds = [];

  const permissions = [
    {
      type: 'user',
      role: 'writer',
      emailAddress: targetUserEmail, // '[email protected]',
    },
    {
      type: 'domain',
      role: 'writer',
      domain: targetDomainName, // 'example.com',
    },
  ];
  // Note: Client library does not currently support HTTP batch
  // requests. When possible, use batched requests when inserting
  // multiple permissions on the same item. For this sample,
  // permissions are inserted serially.
  for (const permission of permissions) {
    try {
      const result = await service.permissions.create({
        resource: permission,
        fileId: fileId,
        fields: 'id',
      });
      permissionIds.push(result.data.id);
      console.log(`Inserted permission id: ${result.data.id}`);
    } catch (err) {
      // TODO(developer): Handle failed permissions
      console.error(err);
    }
  }
  return permissionIds;
}
3 fields used to indicate whether an action can be performed on a file or folder. The Google Drive API sets these fields based on the current user's permissions resource associated with the file or folder.

For example, when Alex logs into your app and tries to share a file, Alex's role is checked in terms of permissions on the file. If the role allows them to share a file, the

/**
 * Batch permission modification
 * @param{string} fileId file ID
 * @param{string} targetUserEmail username
 * @param{string} targetDomainName domain
 * @return{list} permission id
 * */
async function shareFile(fileId, targetUserEmail, targetDomainName) {
  const {GoogleAuth} = require('google-auth-library');
  const {google} = require('googleapis');

  // Get credentials and build service
  // TODO (developer) - Use appropriate auth mechanism for your app
  const auth = new GoogleAuth({
    scopes: 'https://www.googleapis.com/auth/drive',
  });
  const service = google.drive({version: 'v3', auth});
  const permissionIds = [];

  const permissions = [
    {
      type: 'user',
      role: 'writer',
      emailAddress: targetUserEmail, // '[email protected]',
    },
    {
      type: 'domain',
      role: 'writer',
      domain: targetDomainName, // 'example.com',
    },
  ];
  // Note: Client library does not currently support HTTP batch
  // requests. When possible, use batched requests when inserting
  // multiple permissions on the same item. For this sample,
  // permissions are inserted serially.
  for (const permission of permissions) {
    try {
      const result = await service.permissions.create({
        resource: permission,
        fileId: fileId,
        fields: 'id',
      });
      permissionIds.push(result.data.id);
      console.log(`Inserted permission id: ${result.data.id}`);
    } catch (err) {
      // TODO(developer): Handle failed permissions
      console.error(err);
    }
  }
  return permissionIds;
}
3 related to the file, such as
/**
 * Batch permission modification
 * @param{string} fileId file ID
 * @param{string} targetUserEmail username
 * @param{string} targetDomainName domain
 * @return{list} permission id
 * */
async function shareFile(fileId, targetUserEmail, targetDomainName) {
  const {GoogleAuth} = require('google-auth-library');
  const {google} = require('googleapis');

  // Get credentials and build service
  // TODO (developer) - Use appropriate auth mechanism for your app
  const auth = new GoogleAuth({
    scopes: 'https://www.googleapis.com/auth/drive',
  });
  const service = google.drive({version: 'v3', auth});
  const permissionIds = [];

  const permissions = [
    {
      type: 'user',
      role: 'writer',
      emailAddress: targetUserEmail, // '[email protected]',
    },
    {
      type: 'domain',
      role: 'writer',
      domain: targetDomainName, // 'example.com',
    },
  ];
  // Note: Client library does not currently support HTTP batch
  // requests. When possible, use batched requests when inserting
  // multiple permissions on the same item. For this sample,
  // permissions are inserted serially.
  for (const permission of permissions) {
    try {
      const result = await service.permissions.create({
        resource: permission,
        fileId: fileId,
        fields: 'id',
      });
      permissionIds.push(result.data.id);
      console.log(`Inserted permission id: ${result.data.id}`);
    } catch (err) {
      // TODO(developer): Handle failed permissions
      console.error(err);
    }
  }
  return permissionIds;
}
5, are filled in relative to the role. If Alex wants to share the file, your app checks the
/**
 * Batch permission modification
 * @param{string} fileId file ID
 * @param{string} targetUserEmail username
 * @param{string} targetDomainName domain
 * @return{list} permission id
 * */
async function shareFile(fileId, targetUserEmail, targetDomainName) {
  const {GoogleAuth} = require('google-auth-library');
  const {google} = require('googleapis');

  // Get credentials and build service
  // TODO (developer) - Use appropriate auth mechanism for your app
  const auth = new GoogleAuth({
    scopes: 'https://www.googleapis.com/auth/drive',
  });
  const service = google.drive({version: 'v3', auth});
  const permissionIds = [];

  const permissions = [
    {
      type: 'user',
      role: 'writer',
      emailAddress: targetUserEmail, // '[email protected]',
    },
    {
      type: 'domain',
      role: 'writer',
      domain: targetDomainName, // 'example.com',
    },
  ];
  // Note: Client library does not currently support HTTP batch
  // requests. When possible, use batched requests when inserting
  // multiple permissions on the same item. For this sample,
  // permissions are inserted serially.
  for (const permission of permissions) {
    try {
      const result = await service.permissions.create({
        resource: permission,
        fileId: fileId,
        fields: 'id',
      });
      permissionIds.push(result.data.id);
      console.log(`Inserted permission id: ${result.data.id}`);
    } catch (err) {
      // TODO(developer): Handle failed permissions
      console.error(err);
    }
  }
  return permissionIds;
}
3 to ensure
/**
 * Batch permission modification
 * @param{string} fileId file ID
 * @param{string} targetUserEmail username
 * @param{string} targetDomainName domain
 * @return{list} permission id
 * */
async function shareFile(fileId, targetUserEmail, targetDomainName) {
  const {GoogleAuth} = require('google-auth-library');
  const {google} = require('googleapis');

  // Get credentials and build service
  // TODO (developer) - Use appropriate auth mechanism for your app
  const auth = new GoogleAuth({
    scopes: 'https://www.googleapis.com/auth/drive',
  });
  const service = google.drive({version: 'v3', auth});
  const permissionIds = [];

  const permissions = [
    {
      type: 'user',
      role: 'writer',
      emailAddress: targetUserEmail, // '[email protected]',
    },
    {
      type: 'domain',
      role: 'writer',
      domain: targetDomainName, // 'example.com',
    },
  ];
  // Note: Client library does not currently support HTTP batch
  // requests. When possible, use batched requests when inserting
  // multiple permissions on the same item. For this sample,
  // permissions are inserted serially.
  for (const permission of permissions) {
    try {
      const result = await service.permissions.create({
        resource: permission,
        fileId: fileId,
        fields: 'id',
      });
      permissionIds.push(result.data.id);
      console.log(`Inserted permission id: ${result.data.id}`);
    } catch (err) {
      // TODO(developer): Handle failed permissions
      console.error(err);
    }
  }
  return permissionIds;
}
5 is set to
/**
 * Batch permission modification
 * @param{string} fileId file ID
 * @param{string} targetUserEmail username
 * @param{string} targetDomainName domain
 * @return{list} permission id
 * */
async function shareFile(fileId, targetUserEmail, targetDomainName) {
  const {GoogleAuth} = require('google-auth-library');
  const {google} = require('googleapis');

  // Get credentials and build service
  // TODO (developer) - Use appropriate auth mechanism for your app
  const auth = new GoogleAuth({
    scopes: 'https://www.googleapis.com/auth/drive',
  });
  const service = google.drive({version: 'v3', auth});
  const permissionIds = [];

  const permissions = [
    {
      type: 'user',
      role: 'writer',
      emailAddress: targetUserEmail, // '[email protected]',
    },
    {
      type: 'domain',
      role: 'writer',
      domain: targetDomainName, // 'example.com',
    },
  ];
  // Note: Client library does not currently support HTTP batch
  // requests. When possible, use batched requests when inserting
  // multiple permissions on the same item. For this sample,
  // permissions are inserted serially.
  for (const permission of permissions) {
    try {
      const result = await service.permissions.create({
        resource: permission,
        fileId: fileId,
        fields: 'id',
      });
      permissionIds.push(result.data.id);
      console.log(`Inserted permission id: ${result.data.id}`);
    } catch (err) {
      // TODO(developer): Handle failed permissions
      console.error(err);
    }
  }
  return permissionIds;
}
8.

Create a permission

The following 2 fields are necessary when creating a permission:

  • type—The type identifies the scope of the permission (

    use Google\Client;
    use Google\Service\Drive;
    function shareFile()
    {
        try {
            $client = new Client();
            $client->useApplicationDefaultCredentials();
            $client->addScope(Drive::DRIVE);
            $driveService = new Drive($client);
            $realFileId = readline("Enter File Id: ");
            $realUser = readline("Enter user email address: ");
            $realDomain = readline("Enter domain name: ");
            $ids = array();
                $fileId = '1sTWaJ_j7PkjzaBWtNc3IzovK5hQf21FbOw9yLeeLPNQ';
                $fileId = $realFileId;
                $driveService->getClient()->setUseBatch(true);
                try {
                    $batch = $driveService->createBatch();
    
                    $userPermission = new Drive\Permission(array(
                        'type' => 'user',
                        'role' => 'writer',
                        'emailAddress' => '[email protected]'
                    ));
                    $userPermission['emailAddress'] = $realUser;
                    $request = $driveService->permissions->create(
                        $fileId, $userPermission, array('fields' => 'id'));
                    $batch->add($request, 'user');
                    $domainPermission = new Drive\Permission(array(
                        'type' => 'domain',
                        'role' => 'reader',
                        'domain' => 'example.com'
                    ));
                    $userPermission['domain'] = $realDomain;
                    $request = $driveService->permissions->create(
                        $fileId, $domainPermission, array('fields' => 'id'));
                    $batch->add($request, 'domain');
                    $results = $batch->execute();
    
                    foreach ($results as $result) {
                        if ($result instanceof Google_Service_Exception) {
                            // Handle error
                            printf($result);
                        } else {
                            printf("Permission ID: %s\n", $result->id);
                            array_push($ids, $result->id);
                        }
                    }
                } finally {
                    $driveService->getClient()->setUseBatch(false);
                }
                return $ids;
        } catch(Exception $e) {
            echo "Error Message: ".$e;
        }
    
    }
    1,
    use Google\Client;
    use Google\Service\Drive;
    function shareFile()
    {
        try {
            $client = new Client();
            $client->useApplicationDefaultCredentials();
            $client->addScope(Drive::DRIVE);
            $driveService = new Drive($client);
            $realFileId = readline("Enter File Id: ");
            $realUser = readline("Enter user email address: ");
            $realDomain = readline("Enter domain name: ");
            $ids = array();
                $fileId = '1sTWaJ_j7PkjzaBWtNc3IzovK5hQf21FbOw9yLeeLPNQ';
                $fileId = $realFileId;
                $driveService->getClient()->setUseBatch(true);
                try {
                    $batch = $driveService->createBatch();
    
                    $userPermission = new Drive\Permission(array(
                        'type' => 'user',
                        'role' => 'writer',
                        'emailAddress' => '[email protected]'
                    ));
                    $userPermission['emailAddress'] = $realUser;
                    $request = $driveService->permissions->create(
                        $fileId, $userPermission, array('fields' => 'id'));
                    $batch->add($request, 'user');
                    $domainPermission = new Drive\Permission(array(
                        'type' => 'domain',
                        'role' => 'reader',
                        'domain' => 'example.com'
                    ));
                    $userPermission['domain'] = $realDomain;
                    $request = $driveService->permissions->create(
                        $fileId, $domainPermission, array('fields' => 'id'));
                    $batch->add($request, 'domain');
                    $results = $batch->execute();
    
                    foreach ($results as $result) {
                        if ($result instanceof Google_Service_Exception) {
                            // Handle error
                            printf($result);
                        } else {
                            printf("Permission ID: %s\n", $result->id);
                            array_push($ids, $result->id);
                        }
                    }
                } finally {
                    $driveService->getClient()->setUseBatch(false);
                }
                return $ids;
        } catch(Exception $e) {
            echo "Error Message: ".$e;
        }
    
    }
    2,
    use Google\Client;
    use Google\Service\Drive;
    function shareFile()
    {
        try {
            $client = new Client();
            $client->useApplicationDefaultCredentials();
            $client->addScope(Drive::DRIVE);
            $driveService = new Drive($client);
            $realFileId = readline("Enter File Id: ");
            $realUser = readline("Enter user email address: ");
            $realDomain = readline("Enter domain name: ");
            $ids = array();
                $fileId = '1sTWaJ_j7PkjzaBWtNc3IzovK5hQf21FbOw9yLeeLPNQ';
                $fileId = $realFileId;
                $driveService->getClient()->setUseBatch(true);
                try {
                    $batch = $driveService->createBatch();
    
                    $userPermission = new Drive\Permission(array(
                        'type' => 'user',
                        'role' => 'writer',
                        'emailAddress' => '[email protected]'
                    ));
                    $userPermission['emailAddress'] = $realUser;
                    $request = $driveService->permissions->create(
                        $fileId, $userPermission, array('fields' => 'id'));
                    $batch->add($request, 'user');
                    $domainPermission = new Drive\Permission(array(
                        'type' => 'domain',
                        'role' => 'reader',
                        'domain' => 'example.com'
                    ));
                    $userPermission['domain'] = $realDomain;
                    $request = $driveService->permissions->create(
                        $fileId, $domainPermission, array('fields' => 'id'));
                    $batch->add($request, 'domain');
                    $results = $batch->execute();
    
                    foreach ($results as $result) {
                        if ($result instanceof Google_Service_Exception) {
                            // Handle error
                            printf($result);
                        } else {
                            printf("Permission ID: %s\n", $result->id);
                            array_push($ids, $result->id);
                        }
                    }
                } finally {
                    $driveService->getClient()->setUseBatch(false);
                }
                return $ids;
        } catch(Exception $e) {
            echo "Error Message: ".$e;
        }
    
    }
    3, or
    use Google\Client;
    use Google\Service\Drive;
    function shareFile()
    {
        try {
            $client = new Client();
            $client->useApplicationDefaultCredentials();
            $client->addScope(Drive::DRIVE);
            $driveService = new Drive($client);
            $realFileId = readline("Enter File Id: ");
            $realUser = readline("Enter user email address: ");
            $realDomain = readline("Enter domain name: ");
            $ids = array();
                $fileId = '1sTWaJ_j7PkjzaBWtNc3IzovK5hQf21FbOw9yLeeLPNQ';
                $fileId = $realFileId;
                $driveService->getClient()->setUseBatch(true);
                try {
                    $batch = $driveService->createBatch();
    
                    $userPermission = new Drive\Permission(array(
                        'type' => 'user',
                        'role' => 'writer',
                        'emailAddress' => '[email protected]'
                    ));
                    $userPermission['emailAddress'] = $realUser;
                    $request = $driveService->permissions->create(
                        $fileId, $userPermission, array('fields' => 'id'));
                    $batch->add($request, 'user');
                    $domainPermission = new Drive\Permission(array(
                        'type' => 'domain',
                        'role' => 'reader',
                        'domain' => 'example.com'
                    ));
                    $userPermission['domain'] = $realDomain;
                    $request = $driveService->permissions->create(
                        $fileId, $domainPermission, array('fields' => 'id'));
                    $batch->add($request, 'domain');
                    $results = $batch->execute();
    
                    foreach ($results as $result) {
                        if ($result instanceof Google_Service_Exception) {
                            // Handle error
                            printf($result);
                        } else {
                            printf("Permission ID: %s\n", $result->id);
                            array_push($ids, $result->id);
                        }
                    }
                } finally {
                    $driveService->getClient()->setUseBatch(false);
                }
                return $ids;
        } catch(Exception $e) {
            echo "Error Message: ".$e;
        }
    
    }
    4). A permission with type=user applies to a specific user whereas a permission with
    use Google\Client;
    use Google\Service\Drive;
    function shareFile()
    {
        try {
            $client = new Client();
            $client->useApplicationDefaultCredentials();
            $client->addScope(Drive::DRIVE);
            $driveService = new Drive($client);
            $realFileId = readline("Enter File Id: ");
            $realUser = readline("Enter user email address: ");
            $realDomain = readline("Enter domain name: ");
            $ids = array();
                $fileId = '1sTWaJ_j7PkjzaBWtNc3IzovK5hQf21FbOw9yLeeLPNQ';
                $fileId = $realFileId;
                $driveService->getClient()->setUseBatch(true);
                try {
                    $batch = $driveService->createBatch();
    
                    $userPermission = new Drive\Permission(array(
                        'type' => 'user',
                        'role' => 'writer',
                        'emailAddress' => '[email protected]'
                    ));
                    $userPermission['emailAddress'] = $realUser;
                    $request = $driveService->permissions->create(
                        $fileId, $userPermission, array('fields' => 'id'));
                    $batch->add($request, 'user');
                    $domainPermission = new Drive\Permission(array(
                        'type' => 'domain',
                        'role' => 'reader',
                        'domain' => 'example.com'
                    ));
                    $userPermission['domain'] = $realDomain;
                    $request = $driveService->permissions->create(
                        $fileId, $domainPermission, array('fields' => 'id'));
                    $batch->add($request, 'domain');
                    $results = $batch->execute();
    
                    foreach ($results as $result) {
                        if ($result instanceof Google_Service_Exception) {
                            // Handle error
                            printf($result);
                        } else {
                            printf("Permission ID: %s\n", $result->id);
                            array_push($ids, $result->id);
                        }
                    }
                } finally {
                    $driveService->getClient()->setUseBatch(false);
                }
                return $ids;
        } catch(Exception $e) {
            echo "Error Message: ".$e;
        }
    
    }
    6 applies to everyone in a specific domain.

  • role—The role field identifies the operations that the type can perform. For example, a permission with type=user and role=reader grants a specific user read-only access to the file or folder. Or, a permission with

    use Google\Client;
    use Google\Service\Drive;
    function shareFile()
    {
        try {
            $client = new Client();
            $client->useApplicationDefaultCredentials();
            $client->addScope(Drive::DRIVE);
            $driveService = new Drive($client);
            $realFileId = readline("Enter File Id: ");
            $realUser = readline("Enter user email address: ");
            $realDomain = readline("Enter domain name: ");
            $ids = array();
                $fileId = '1sTWaJ_j7PkjzaBWtNc3IzovK5hQf21FbOw9yLeeLPNQ';
                $fileId = $realFileId;
                $driveService->getClient()->setUseBatch(true);
                try {
                    $batch = $driveService->createBatch();
    
                    $userPermission = new Drive\Permission(array(
                        'type' => 'user',
                        'role' => 'writer',
                        'emailAddress' => '[email protected]'
                    ));
                    $userPermission['emailAddress'] = $realUser;
                    $request = $driveService->permissions->create(
                        $fileId, $userPermission, array('fields' => 'id'));
                    $batch->add($request, 'user');
                    $domainPermission = new Drive\Permission(array(
                        'type' => 'domain',
                        'role' => 'reader',
                        'domain' => 'example.com'
                    ));
                    $userPermission['domain'] = $realDomain;
                    $request = $driveService->permissions->create(
                        $fileId, $domainPermission, array('fields' => 'id'));
                    $batch->add($request, 'domain');
                    $results = $batch->execute();
    
                    foreach ($results as $result) {
                        if ($result instanceof Google_Service_Exception) {
                            // Handle error
                            printf($result);
                        } else {
                            printf("Permission ID: %s\n", $result->id);
                            array_push($ids, $result->id);
                        }
                    }
                } finally {
                    $driveService->getClient()->setUseBatch(false);
                }
                return $ids;
        } catch(Exception $e) {
            echo "Error Message: ".$e;
        }
    
    }
    6 and
    from __future__ import print_function
    
    import google.auth
    from googleapiclient.discovery import build
    from googleapiclient.errors import HttpError
    
    
    def share_file(real_file_id, real_user, real_domain):
        """Batch permission modification.
        Args:
            real_file_id: file Id
            real_user: User ID
            real_domain: Domain of the user ID
        Prints modified permissions
    
        Load pre-authorized user credentials from the environment.
        TODO(developer) - See https://developers.google.com/identity
        for guides on implementing OAuth2 for the application.
        """
        creds, _ = google.auth.default()
    
        try:
            # create drive api client
            service = build('drive', 'v3', credentials=creds)
            ids = []
            file_id = real_file_id
    
            def callback(request_id, response, exception):
                if exception:
                    # Handle error
                    print(exception)
                else:
                    print(f'Request_Id: {request_id}')
                    print(F'Permission Id: {response.get("id")}')
                    ids.append(response.get('id'))
    
            # pylint: disable=maybe-no-member
            batch = service.new_batch_http_request(callback=callback)
            user_permission = {
                'type': 'user',
                'role': 'writer',
                'emailAddress': '[email protected]'
            }
            batch.add(service.permissions().create(fileId=file_id,
                                                   body=user_permission,
                                                   fields='id',))
            domain_permission = {
                'type': 'domain',
                'role': 'reader',
                'domain': 'example.com'
            }
            domain_permission['domain'] = real_domain
            batch.add(service.permissions().create(fileId=file_id,
                                                   body=domain_permission,
                                                   fields='id',))
            batch.execute()
    
        except HttpError as error:
            print(F'An error occurred: {error}')
            ids = None
    
        return ids
    
    
    if __name__ == '__main__':
        share_file(real_file_id='1dUiRSoAQKkM3a4nTPeNQWgiuau1KdQ_l',
                   real_user='[email protected]',
                   real_domain='workspacesamples.dev')
    0 lets everyone in the domain add comments to a file. For a complete list of roles and the operations permitted by each, refer to Roles.

When you create a permission where type=user or type=group, you must also provide an

using Google.Apis.Auth.OAuth2;
using Google.Apis.Drive.v3;
using Google.Apis.Drive.v3.Data;
using Google.Apis.Requests;
using Google.Apis.Services;

namespace DriveV3Snippets
{
    // Class to demonstrate use-case of Drive modify permissions.
    public class ShareFile
    {
        /// <summary>
        /// Batch permission modification.
        /// </summary>
        /// <param name="realFileId">File id.</param>
        /// <param name="realUser">User id.</param>
        /// <param name="realDomain">Domain id.</param>
        /// <returns>list of modified permissions, null otherwise.</returns>
        public static IList<String> DriveShareFile(string realFileId, string realUser, string realDomain)
        {
            try
            {
                /* Load pre-authorized user credentials from the environment.
                 TODO(developer) - See https://developers.google.com/identity for
                 guides on implementing OAuth2 for your application. */
                GoogleCredential credential = GoogleCredential.GetApplicationDefault()
                    .CreateScoped(DriveService.Scope.Drive);

                // Create Drive API service.
                var service = new DriveService(new BaseClientService.Initializer
                {
                    HttpClientInitializer = credential,
                    ApplicationName = "Drive API Snippets"
                });

                var ids = new List<String>();
                var batch = new BatchRequest(service);
                BatchRequest.OnResponse<Permission> callback = delegate(
                    Permission permission,
                    RequestError error,
                    int index,
                    HttpResponseMessage message)
                {
                    if (error != null)
                    {
                        // Handle error
                        Console.WriteLine(error.Message);
                    }
                    else
                    {
                        Console.WriteLine("Permission ID: " + permission.Id);
                    }
                };
                Permission userPermission = new Permission()
                {
                    Type = "user",
                    Role = "writer",
                    EmailAddress = realUser
                };

                var request = service.Permissions.Create(userPermission, realFileId);
                request.Fields = "id";
                batch.Queue(request, callback);

                Permission domainPermission = new Permission()
                {
                    Type = "domain",
                    Role = "reader",
                    Domain = realDomain
                };
                request = service.Permissions.Create(domainPermission, realFileId);
                request.Fields = "id";
                batch.Queue(request, callback);
                var task = batch.ExecuteAsync();
                task.Wait();
                return ids;
            }
            catch (Exception e)
            {
                // TODO(developer) - handle error appropriately
                if (e is AggregateException)
                {
                    Console.WriteLine("Credential Not found");
                }
                else
                {
                    throw;
                }
            }
            return null;
        }
    }
}
6 to tie the specific user or group to the permission.

When you create a permission where

use Google\Client;
use Google\Service\Drive;
function shareFile()
{
    try {
        $client = new Client();
        $client->useApplicationDefaultCredentials();
        $client->addScope(Drive::DRIVE);
        $driveService = new Drive($client);
        $realFileId = readline("Enter File Id: ");
        $realUser = readline("Enter user email address: ");
        $realDomain = readline("Enter domain name: ");
        $ids = array();
            $fileId = '1sTWaJ_j7PkjzaBWtNc3IzovK5hQf21FbOw9yLeeLPNQ';
            $fileId = $realFileId;
            $driveService->getClient()->setUseBatch(true);
            try {
                $batch = $driveService->createBatch();

                $userPermission = new Drive\Permission(array(
                    'type' => 'user',
                    'role' => 'writer',
                    'emailAddress' => '[email protected]'
                ));
                $userPermission['emailAddress'] = $realUser;
                $request = $driveService->permissions->create(
                    $fileId, $userPermission, array('fields' => 'id'));
                $batch->add($request, 'user');
                $domainPermission = new Drive\Permission(array(
                    'type' => 'domain',
                    'role' => 'reader',
                    'domain' => 'example.com'
                ));
                $userPermission['domain'] = $realDomain;
                $request = $driveService->permissions->create(
                    $fileId, $domainPermission, array('fields' => 'id'));
                $batch->add($request, 'domain');
                $results = $batch->execute();

                foreach ($results as $result) {
                    if ($result instanceof Google_Service_Exception) {
                        // Handle error
                        printf($result);
                    } else {
                        printf("Permission ID: %s\n", $result->id);
                        array_push($ids, $result->id);
                    }
                }
            } finally {
                $driveService->getClient()->setUseBatch(false);
            }
            return $ids;
    } catch(Exception $e) {
        echo "Error Message: ".$e;
    }

}
6, you must also provide a
use Google\Client;
use Google\Service\Drive;
function shareFile()
{
    try {
        $client = new Client();
        $client->useApplicationDefaultCredentials();
        $client->addScope(Drive::DRIVE);
        $driveService = new Drive($client);
        $realFileId = readline("Enter File Id: ");
        $realUser = readline("Enter user email address: ");
        $realDomain = readline("Enter domain name: ");
        $ids = array();
            $fileId = '1sTWaJ_j7PkjzaBWtNc3IzovK5hQf21FbOw9yLeeLPNQ';
            $fileId = $realFileId;
            $driveService->getClient()->setUseBatch(true);
            try {
                $batch = $driveService->createBatch();

                $userPermission = new Drive\Permission(array(
                    'type' => 'user',
                    'role' => 'writer',
                    'emailAddress' => '[email protected]'
                ));
                $userPermission['emailAddress'] = $realUser;
                $request = $driveService->permissions->create(
                    $fileId, $userPermission, array('fields' => 'id'));
                $batch->add($request, 'user');
                $domainPermission = new Drive\Permission(array(
                    'type' => 'domain',
                    'role' => 'reader',
                    'domain' => 'example.com'
                ));
                $userPermission['domain'] = $realDomain;
                $request = $driveService->permissions->create(
                    $fileId, $domainPermission, array('fields' => 'id'));
                $batch->add($request, 'domain');
                $results = $batch->execute();

                foreach ($results as $result) {
                    if ($result instanceof Google_Service_Exception) {
                        // Handle error
                        printf($result);
                    } else {
                        printf("Permission ID: %s\n", $result->id);
                        array_push($ids, $result->id);
                    }
                }
            } finally {
                $driveService->getClient()->setUseBatch(false);
            }
            return $ids;
    } catch(Exception $e) {
        echo "Error Message: ".$e;
    }

}
3 to tie a specific domain to the permission.

To create a permission:

  1. Use the
    using Google.Apis.Auth.OAuth2;
    using Google.Apis.Drive.v3;
    using Google.Apis.Drive.v3.Data;
    using Google.Apis.Requests;
    using Google.Apis.Services;
    
    namespace DriveV3Snippets
    {
        // Class to demonstrate use-case of Drive modify permissions.
        public class ShareFile
        {
            /// <summary>
            /// Batch permission modification.
            /// </summary>
            /// <param name="realFileId">File id.</param>
            /// <param name="realUser">User id.</param>
            /// <param name="realDomain">Domain id.</param>
            /// <returns>list of modified permissions, null otherwise.</returns>
            public static IList<String> DriveShareFile(string realFileId, string realUser, string realDomain)
            {
                try
                {
                    /* Load pre-authorized user credentials from the environment.
                     TODO(developer) - See https://developers.google.com/identity for
                     guides on implementing OAuth2 for your application. */
                    GoogleCredential credential = GoogleCredential.GetApplicationDefault()
                        .CreateScoped(DriveService.Scope.Drive);
    
                    // Create Drive API service.
                    var service = new DriveService(new BaseClientService.Initializer
                    {
                        HttpClientInitializer = credential,
                        ApplicationName = "Drive API Snippets"
                    });
    
                    var ids = new List<String>();
                    var batch = new BatchRequest(service);
                    BatchRequest.OnResponse<Permission> callback = delegate(
                        Permission permission,
                        RequestError error,
                        int index,
                        HttpResponseMessage message)
                    {
                        if (error != null)
                        {
                            // Handle error
                            Console.WriteLine(error.Message);
                        }
                        else
                        {
                            Console.WriteLine("Permission ID: " + permission.Id);
                        }
                    };
                    Permission userPermission = new Permission()
                    {
                        Type = "user",
                        Role = "writer",
                        EmailAddress = realUser
                    };
    
                    var request = service.Permissions.Create(userPermission, realFileId);
                    request.Fields = "id";
                    batch.Queue(request, callback);
    
                    Permission domainPermission = new Permission()
                    {
                        Type = "domain",
                        Role = "reader",
                        Domain = realDomain
                    };
                    request = service.Permissions.Create(domainPermission, realFileId);
                    request.Fields = "id";
                    batch.Queue(request, callback);
                    var task = batch.ExecuteAsync();
                    task.Wait();
                    return ids;
                }
                catch (Exception e)
                {
                    // TODO(developer) - handle error appropriately
                    if (e is AggregateException)
                    {
                        Console.WriteLine("Credential Not found");
                    }
                    else
                    {
                        throw;
                    }
                }
                return null;
            }
        }
    }
    9 method with the type0 for the associated file or folder.
  2. In the request body, identify the type and role.
  3. If type=user or type=group, provide an
    using Google.Apis.Auth.OAuth2;
    using Google.Apis.Drive.v3;
    using Google.Apis.Drive.v3.Data;
    using Google.Apis.Requests;
    using Google.Apis.Services;
    
    namespace DriveV3Snippets
    {
        // Class to demonstrate use-case of Drive modify permissions.
        public class ShareFile
        {
            /// <summary>
            /// Batch permission modification.
            /// </summary>
            /// <param name="realFileId">File id.</param>
            /// <param name="realUser">User id.</param>
            /// <param name="realDomain">Domain id.</param>
            /// <returns>list of modified permissions, null otherwise.</returns>
            public static IList<String> DriveShareFile(string realFileId, string realUser, string realDomain)
            {
                try
                {
                    /* Load pre-authorized user credentials from the environment.
                     TODO(developer) - See https://developers.google.com/identity for
                     guides on implementing OAuth2 for your application. */
                    GoogleCredential credential = GoogleCredential.GetApplicationDefault()
                        .CreateScoped(DriveService.Scope.Drive);
    
                    // Create Drive API service.
                    var service = new DriveService(new BaseClientService.Initializer
                    {
                        HttpClientInitializer = credential,
                        ApplicationName = "Drive API Snippets"
                    });
    
                    var ids = new List<String>();
                    var batch = new BatchRequest(service);
                    BatchRequest.OnResponse<Permission> callback = delegate(
                        Permission permission,
                        RequestError error,
                        int index,
                        HttpResponseMessage message)
                    {
                        if (error != null)
                        {
                            // Handle error
                            Console.WriteLine(error.Message);
                        }
                        else
                        {
                            Console.WriteLine("Permission ID: " + permission.Id);
                        }
                    };
                    Permission userPermission = new Permission()
                    {
                        Type = "user",
                        Role = "writer",
                        EmailAddress = realUser
                    };
    
                    var request = service.Permissions.Create(userPermission, realFileId);
                    request.Fields = "id";
                    batch.Queue(request, callback);
    
                    Permission domainPermission = new Permission()
                    {
                        Type = "domain",
                        Role = "reader",
                        Domain = realDomain
                    };
                    request = service.Permissions.Create(domainPermission, realFileId);
                    request.Fields = "id";
                    batch.Queue(request, callback);
                    var task = batch.ExecuteAsync();
                    task.Wait();
                    return ids;
                }
                catch (Exception e)
                {
                    // TODO(developer) - handle error appropriately
                    if (e is AggregateException)
                    {
                        Console.WriteLine("Credential Not found");
                    }
                    else
                    {
                        throw;
                    }
                }
                return null;
            }
        }
    }
    6. If
    use Google\Client;
    use Google\Service\Drive;
    function shareFile()
    {
        try {
            $client = new Client();
            $client->useApplicationDefaultCredentials();
            $client->addScope(Drive::DRIVE);
            $driveService = new Drive($client);
            $realFileId = readline("Enter File Id: ");
            $realUser = readline("Enter user email address: ");
            $realDomain = readline("Enter domain name: ");
            $ids = array();
                $fileId = '1sTWaJ_j7PkjzaBWtNc3IzovK5hQf21FbOw9yLeeLPNQ';
                $fileId = $realFileId;
                $driveService->getClient()->setUseBatch(true);
                try {
                    $batch = $driveService->createBatch();
    
                    $userPermission = new Drive\Permission(array(
                        'type' => 'user',
                        'role' => 'writer',
                        'emailAddress' => '[email protected]'
                    ));
                    $userPermission['emailAddress'] = $realUser;
                    $request = $driveService->permissions->create(
                        $fileId, $userPermission, array('fields' => 'id'));
                    $batch->add($request, 'user');
                    $domainPermission = new Drive\Permission(array(
                        'type' => 'domain',
                        'role' => 'reader',
                        'domain' => 'example.com'
                    ));
                    $userPermission['domain'] = $realDomain;
                    $request = $driveService->permissions->create(
                        $fileId, $domainPermission, array('fields' => 'id'));
                    $batch->add($request, 'domain');
                    $results = $batch->execute();
    
                    foreach ($results as $result) {
                        if ($result instanceof Google_Service_Exception) {
                            // Handle error
                            printf($result);
                        } else {
                            printf("Permission ID: %s\n", $result->id);
                            array_push($ids, $result->id);
                        }
                    }
                } finally {
                    $driveService->getClient()->setUseBatch(false);
                }
                return $ids;
        } catch(Exception $e) {
            echo "Error Message: ".$e;
        }
    
    }
    6, provide a
    use Google\Client;
    use Google\Service\Drive;
    function shareFile()
    {
        try {
            $client = new Client();
            $client->useApplicationDefaultCredentials();
            $client->addScope(Drive::DRIVE);
            $driveService = new Drive($client);
            $realFileId = readline("Enter File Id: ");
            $realUser = readline("Enter user email address: ");
            $realDomain = readline("Enter domain name: ");
            $ids = array();
                $fileId = '1sTWaJ_j7PkjzaBWtNc3IzovK5hQf21FbOw9yLeeLPNQ';
                $fileId = $realFileId;
                $driveService->getClient()->setUseBatch(true);
                try {
                    $batch = $driveService->createBatch();
    
                    $userPermission = new Drive\Permission(array(
                        'type' => 'user',
                        'role' => 'writer',
                        'emailAddress' => '[email protected]'
                    ));
                    $userPermission['emailAddress'] = $realUser;
                    $request = $driveService->permissions->create(
                        $fileId, $userPermission, array('fields' => 'id'));
                    $batch->add($request, 'user');
                    $domainPermission = new Drive\Permission(array(
                        'type' => 'domain',
                        'role' => 'reader',
                        'domain' => 'example.com'
                    ));
                    $userPermission['domain'] = $realDomain;
                    $request = $driveService->permissions->create(
                        $fileId, $domainPermission, array('fields' => 'id'));
                    $batch->add($request, 'domain');
                    $results = $batch->execute();
    
                    foreach ($results as $result) {
                        if ($result instanceof Google_Service_Exception) {
                            // Handle error
                            printf($result);
                        } else {
                            printf("Permission ID: %s\n", $result->id);
                            array_push($ids, $result->id);
                        }
                    }
                } finally {
                    $driveService->getClient()->setUseBatch(false);
                }
                return $ids;
        } catch(Exception $e) {
            echo "Error Message: ".$e;
        }
    
    }
    3.

Retrieve all permissions for a file, folder, or shared drive

Use the type8 method to retrieve all permissions for a file, folder, or shared drive.

Verify user permissions

When your app opens a file, it should check the file's capabilities and render the UI to reflect the permissions of the current user. For example, if the user doesn't have a type9 capability on the file, the ability to comment should be disabled in the UI.

To check the capabilities, call role0 with the type0 and the role2 parameter set to the

/**
 * Batch permission modification
 * @param{string} fileId file ID
 * @param{string} targetUserEmail username
 * @param{string} targetDomainName domain
 * @return{list} permission id
 * */
async function shareFile(fileId, targetUserEmail, targetDomainName) {
  const {GoogleAuth} = require('google-auth-library');
  const {google} = require('googleapis');

  // Get credentials and build service
  // TODO (developer) - Use appropriate auth mechanism for your app
  const auth = new GoogleAuth({
    scopes: 'https://www.googleapis.com/auth/drive',
  });
  const service = google.drive({version: 'v3', auth});
  const permissionIds = [];

  const permissions = [
    {
      type: 'user',
      role: 'writer',
      emailAddress: targetUserEmail, // '[email protected]',
    },
    {
      type: 'domain',
      role: 'writer',
      domain: targetDomainName, // 'example.com',
    },
  ];
  // Note: Client library does not currently support HTTP batch
  // requests. When possible, use batched requests when inserting
  // multiple permissions on the same item. For this sample,
  // permissions are inserted serially.
  for (const permission of permissions) {
    try {
      const result = await service.permissions.create({
        resource: permission,
        fileId: fileId,
        fields: 'id',
      });
      permissionIds.push(result.data.id);
      console.log(`Inserted permission id: ${result.data.id}`);
    } catch (err) {
      // TODO(developer): Handle failed permissions
      console.error(err);
    }
  }
  return permissionIds;
}
3 field.

For further information on returning fields using the role2 parameter, refer to Return specific fields for a file.

Determine the source of the role for shared drive files & folders

To change the role on a file or folder, you must know the source of the role. For shared drives, the source of a role can be based on membership to the shared drive, the role on a folder, or the role on a file.

To determine the source of the role for a shared drive, or items within that drive, call role5 with the type0, the role7, and the role2 parameter set to the role9 field. To find the role7, use type8 with the type0.

This field enumerates all inherited and direct file permissions for the user, group, or domain.

Change permissions

To change permissions on a file or folder, you can change the assigned role:

  1. Call type=user3 with the role7 of the permission to change and the type0 for the associated file, folder, or shared drive. To find the role7, use type8 with the type0.

    Note: The role7 represents the user or group to which the permission is granted, such as role=reader0 or role=reader1. The role7 remains the same for that user or group across all files, folders, and shared drives.
  2. In the request, identify the new role.

You can grant permissions on individual files or folders in a shared drive even if the user or group is already a member. For example, Alex has the role of

/**
 * Batch permission modification
 * @param{string} fileId file ID
 * @param{string} targetUserEmail username
 * @param{string} targetDomainName domain
 * @return{list} permission id
 * */
async function shareFile(fileId, targetUserEmail, targetDomainName) {
  const {GoogleAuth} = require('google-auth-library');
  const {google} = require('googleapis');

  // Get credentials and build service
  // TODO (developer) - Use appropriate auth mechanism for your app
  const auth = new GoogleAuth({
    scopes: 'https://www.googleapis.com/auth/drive',
  });
  const service = google.drive({version: 'v3', auth});
  const permissionIds = [];

  const permissions = [
    {
      type: 'user',
      role: 'writer',
      emailAddress: targetUserEmail, // '[email protected]',
    },
    {
      type: 'domain',
      role: 'writer',
      domain: targetDomainName, // 'example.com',
    },
  ];
  // Note: Client library does not currently support HTTP batch
  // requests. When possible, use batched requests when inserting
  // multiple permissions on the same item. For this sample,
  // permissions are inserted serially.
  for (const permission of permissions) {
    try {
      const result = await service.permissions.create({
        resource: permission,
        fileId: fileId,
        fields: 'id',
      });
      permissionIds.push(result.data.id);
      console.log(`Inserted permission id: ${result.data.id}`);
    } catch (err) {
      // TODO(developer): Handle failed permissions
      console.error(err);
    }
  }
  return permissionIds;
}
2 as part of their membership to a shared drive. However, your app can grant Alex the role=reader5 role for a file in a shared drive. In this case, because the new role is more permissive than the role granted through their membership, the new permission becomes the effective role for the file or folder.

Revoke access to a file or folder

To revoke access to a file or folder, call role=reader6 with the type0 and the role7 to delete the permission.

For items in "My Drive," it's possible to delete an inherited permission. Deleting an inherited permission revokes access to the item and child items, if any.

For items in a shared drive, inherited permissions cannot be revoked. Update or revoke the permission on the parent file or folder instead.

The role=reader6 operation is also used to delete permissions directly applied to a shared drive file or folder.

Transfer file ownership to another Google Workspace account in the same organization

Ownership of files existing in "My Drive" can be transferred from one Google Workspace account to another account in the same organization. An organization that owns a shared drive owns the files within it. Therefore, ownership transfers are not supported for files and folders in shared drives. Organizers of a shared drive can move items from that shared drive and into their own "My Drive" which transfers the ownership to them.

To transfer ownership of a file in "My Drive", do one of the following:

  • Create a file permission granting a specific user (type=user) owner access (type=group1).

  • Update an existing file's permission with the type=group2 role and transfer ownership to the specified user (type=group3).

Note: When a file is transferred, the previous owner's role is downgraded to role=reader5.

Transfer file ownership from one consumer account to another consumer account

Ownership of files can be transferred between one consumer account to another consumer account. However, Drive doesn't transfer ownership of a file between 2 consumer accounts until the prospective new owner explicitly consents to the transfer. To transfer file ownership from one consumer account to another consumer account:

  1. The current owner initiates an ownership transfer by creating or updating the prospective new owner's file permission. The permission must include these settings: type=group5, type=user, and type=group7. If the new owner is creating a permission for the prospective owner, an email notification is sent to the prospective new owner indicating that they're being asked to assume ownership of the file.

  2. The new owner accepts the ownership transfer request by creating or updating their file permission. The permission must include these settings: type=group1 and type=group3. If the new owner is creating a new permission, an email notification is sent to the previous owner indicating that ownership has been transferred.

When a file is transferred, the previous owner's role is downgraded to role=reader5.

Change multiple permissions with batch requests

We strongly recommend using batch requests to modify multiple permissions.

The following is an example of performing a batch permission modification with a client library.

Note: If you're using the older Drive API v2, you can find code samples in GitHub. Learn how to migrate to Drive API v3.

How do I create a shared folder?

Right-click on the blank space and select "New Folder". Rename the folder to the desired name. Right-click on the new folder and select "Share". The "Share" dialog box will appear.

How do I share a Google Doc to a shared folder?

Share files or folders.
Choose an option: Select one file or folder you want to share. ... .
Click Share or Share ..
In Add people and groups, enter the email address you want to share with..
Choose what permission people will have on the file or folder. Click the Down arrow. ... .
Choose to notify people. ... .
Click Send or Share..

How do I create a folder in Google Docs?

Create a folder.
On your computer, go to drive.google.com..
On the left, click New. Folder..
Enter a name for the folder..
Click Create..