Permissions: insert

Stay organized with collections Save and categorize content based on your preferences.

Inserts a permission for a file or shared drive. Try it now or see an example.

Warning: Concurrent permissions operations on the same file are not supported; only the last update is applied.

Request

HTTP request

POST https://www.googleapis.com/drive/v2/files/fileId/permissions

Parameters

Parameter name Value Description
Path parameters
fileId string The ID for the file or shared drive.
Optional query parameters
emailMessage string A plain text custom message to include in notification emails.
enforceSingleParent boolean Deprecated. See moveToNewOwnersRoot for details. (Default: false)
moveToNewOwnersRoot boolean This parameter will only take effect if the item is not in a shared drive and the request is attempting to transfer the ownership of the item. If set to true, the item will be moved to the new owner's My Drive root folder and all prior parents removed. If set to false, parents are not changed. (Default: false)
sendNotificationEmails boolean Whether to send notification emails when sharing to users or groups. This parameter is ignored and an email is sent if the role is owner. (Default: true)
supportsAllDrives boolean Whether the requesting application supports both My Drives and shared drives. (Default: false)
supportsTeamDrives boolean Deprecated use supportsAllDrives instead. (Default: false)
useDomainAdminAccess boolean Issue the request as a domain administrator; if set to true, then the requester will be granted access if the file ID parameter refers to a shared drive and the requester is an administrator of the domain to which the shared drive belongs. (Default: false)

Authorization

This request requires authorization with at least one of the following scopes:

Scope
https://www.googleapis.com/auth/drive
https://www.googleapis.com/auth/drive.file

Some scopes are restricted and require a security assessment for your app to use them. For more information, see the authentication and authorization page.

Request body

In the request body, supply a Permissions resource with the following properties:

Property name Value Description Notes
Required Properties
role string The primary role for this user. While new values may be supported in the future, the following are currently allowed:
  • owner
  • organizer
  • fileOrganizer
  • writer
  • reader
writable
type string The account type. Allowed values are:
  • user
  • group
  • domain
  • anyone
writable
Optional Properties
additionalRoles[] list Additional roles for this user. Only commenter is currently allowed, though more may be supported in the future. writable
expirationDate datetime The time at which this permission will expire (RFC 3339 date-time). Expiration dates have the following restrictions:
  • They cannot be set on shared drive items
  • They can only be set on user and group permissions
  • The date must be in the future
  • The date cannot be more than a year in the future
writable
id string The ID of the user this permission refers to, and identical to the permissionId in the About and Files resources. When making a drive.permissions.insert request, exactly one of the id or value fields must be specified unless the permission type is anyone, in which case both id and value are ignored. writable
pendingOwner boolean Whether the account associated with this permission is a pending owner. Only populated for user type permissions for files that are not in a shared drive. writable
value string The email address or domain name for the entity. This is used during inserts and is not populated in responses. When making a drive.permissions.insert request, exactly one of the id or value fields must be specified unless the permission type is anyone, in which case both id and value are ignored. writable
view string Indicates the view for this permission. Only populated for permissions that belong to a view. published is the only supported value. writable

Response

If successful, this method returns a Permissions resource in the response body.

Examples

Note: The code examples available for this method do not represent all supported programming languages (see the client libraries page for a list of supported languages).

Java

Uses the Java client library.

import com.google.api.services.drive.Drive;
import com.google.api.services.drive.model.Permission;

import java.io.IOException;
// ...

public class MyClass {

  // ...

  /**
   * Insert a new permission.
   *
   * @param service Drive API service instance.
   * @param fileId ID of the file to insert permission for.
   * @param value User or group e-mail address, domain name or {@code null}
                  "default" type.
   * @param type The value "user", "group", "domain" or "default".
   * @param role The value "owner", "writer" or "reader".
   * @return The inserted permission if successful, {@code null} otherwise.
   */
  private static Permission insertPermission(Drive service, String fileId,
      String value, String type, String role) {
    Permission newPermission = new Permission();

    newPermission.setValue(value);
    newPermission.setType(type);
    newPermission.setRole(role);
    try {
      return service.permissions().insert(fileId, newPermission).execute();
    } catch (IOException e) {
      System.out.println("An error occurred: " + e);
    }
    return null;
  }

  // ...

}

.NET

Uses the .NET client library.

using Google.Apis.Drive.v2;
using Google.Apis.Drive.v2.Data;

using System.Net;
// ...

public class MyClass {

  // ...

  /// <summary>
  /// Insert a new permission.
  /// </summary>
  /// <param name="service">Drive API service instance.</param>
  /// <param name="fileId">ID of the file to insert permission for.</param>
  /// <param name="value">
  /// User or group e-mail address, domain name or null for "default" type.
  /// </param>
  /// <param name="type">The value "user", "group", "domain" or "default".</param>
  /// <param name="role">The value "owner", "writer" or "reader".</param>
  /// <returns>The inserted permission, null is returned if an API error occurred</returns>
  public static Permission InsertPermission(DriveService service, String fileId, String value,
      String type, String role) {
    Permission newPermission = new Permission();
    newPermission.Value = value;
    newPermission.Type = type;
    newPermission.Role = role;
    try {
      return service.Permissions.Insert(newPermission, fileId).Execute();
    } catch (Exception e) {
      Console.WriteLine("An error occurred: " + e.Message);
    }
    return null;
  }

  // ...

}

PHP

Uses the PHP client library.

/**
 * Insert a new permission.
 *
 * @param Google_Service_Drive $service Drive API service instance.
 * @param String $fileId ID of the file to insert permission for.
 * @param String $value User or group e-mail address, domain name or NULL for
                       "default" type.
 * @param String $type The value "user", "group", "domain" or "default".
 * @param String $role The value "owner", "writer" or "reader".
 * @return Google_Servie_Drive_Permission The inserted permission. NULL is
 *     returned if an API error occurred.
 */
function insertPermission($service, $fileId, $value, $type, $role) {
  $newPermission = new Google_Service_Drive_Permission();
  $newPermission->setValue($value);
  $newPermission->setType($type);
  $newPermission->setRole($role);
  try {
    return $service->permissions->insert($fileId, $newPermission);
  } catch (Exception $e) {
    print "An error occurred: " . $e->getMessage();
  }
  return NULL;
}

Python

Uses the Python client library.

from apiclient import errors
# ...

def insert_permission(service, file_id, value, perm_type, role):
  """Insert a new permission.

  Args:
    service: Drive API service instance.
    file_id: ID of the file to insert permission for.
    value: User or group e-mail address, domain name or None for 'default'
           type.
    perm_type: The value 'user', 'group', 'domain' or 'default'.
    role: The value 'owner', 'writer' or 'reader'.
  Returns:
    The inserted permission if successful, None otherwise.
  """
  new_permission = {
      'value': value,
      'type': perm_type,
      'role': role
  }
  try:
    return service.permissions().insert(
        fileId=file_id, body=new_permission).execute()
  except errors.HttpError, error:
    print 'An error occurred: %s' % error
  return None

JavaScript

Uses the JavaScript client library.

/**
 * Insert a new permission.
 *
 * @param {String} fileId ID of the file to insert permission for.
 * @param {String} value User or group e-mail address, domain name or
 *                       {@code null} "default" type.
 * @param {String} type The value "user", "group", "domain" or "default".
 * @param {String} role The value "owner", "writer" or "reader".
 */
function insertPermission(fileId, value, type, role) {
  var body = {
    'value': value,
    'type': type,
    'role': role
  };
  var request = gapi.client.drive.permissions.insert({
    'fileId': fileId,
    'resource': body
  });
  request.execute(function(resp) { });
}

Go

Uses the Go client library.

import (
  "google.golang.org/drive/v2"
  "fmt"
)

// InsertPermission adds a permission to the given file with value type and role
func InsertPermission(d *drive.Service, fileId string, value string,
    permType string, role string) error {
  p := &drive.Permission{Value: value, Type: permType, Role: role}
  _, err := d.Permissions.Insert(fileId, p).Do()
  if err != nil {
    fmt.Printf("An error occurred: %v\n", err)
    return err
  }
  return nil
}

Objective-C

Uses the Objective-C client library.

#import "GTLDrive.h"
// ...

+ (void)insertPermissionWithService:(GTLServiceDrive *)service
                             fileId:(NSString *)fileId
                              value:(NSString *)value
                               type:(NSString *)type
                               role:(NSString *)role
                    completionBlock:(void (^)(GTLDrivePermission* , NSError *))completionBlock {
  GTLDrivePermission *newPermission = [GTLDrivePermission object];
  // User or group e-mail address, domain name or nil for @"default" type.
  newPermission.value = value;
  // The value @"user", @"group", @"domain" or @"default".
  newPermission.type = type;
  // The value @"owner", @"writer" or @"reader".
  newPermission.role = role;

  GTLQueryDrive *query =
    [GTLQueryDrive queryForPermissionsInsertWithObject:newPermission
                                                fileId:fileId];
  // queryTicket can be used to track the status of the request.
  GTLServiceTicket *queryTicket =
    [service executeQuery:query
        completionHandler:^(GTLServiceTicket *ticket,
                            GTLDrivePermission *permission, NSError *error) {
          if (error == nil) {
            completionBlock(permission, nil);
          } else {
            NSLog(@"An error occurred: %@", error);
            completionBlock(nil, error);
          }
        }];
}

// ...

Try it!

Use the APIs Explorer below to call this method on live data and see the response.