Google Drive SDK

Permissions: insert

Requires authorization

Inserts a permission for a file. 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.
Optional query parameters
emailMessage string A custom message to include in notification emails.
sendNotificationEmails boolean Whether to send notification emails when sharing to users or groups. (Default: true)

Authorization

This request requires authorization with at least one of the following scopes (read more about authentication and authorization).

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

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. Allowed values are:
  • owner
  • reader
  • writer


Acceptable values are:
  • "owner":
  • "reader":
  • "writer":
writable
type string The account type. Allowed values are:
  • user
  • group
  • domain
  • anyone


Acceptable values are:
  • "anyone":
  • "domain":
  • "group":
  • "user":
writable
value string The email address or domain name for the entity. This is not populated in responses. You can use the alias me as the value for this property to refer to the current authorized user. writable
Optional Properties
additionalRoles[] list Additional roles for this user. Only commenter is currently allowed. 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).Fetch();
    } catch (Exception e) {
      Console.WriteLine("An error occurred: " + e.Message);
    }
    return null;
  }

  // ...

}

PHP

Uses the PHP client library

/**
 * Insert a new permission.
 *
 * @param Google_DriveService $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_Permission The inserted permission. NULL is returned if an API
                             error occurred.
 */
function insertPermission($service, $fileId, $value, $type, $role) {
  $newPermission = new Google_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

Ruby

Uses the Ruby client library

##
# Insert a new permission
#
# @param [Google::APIClient] client
#   Authorized client instance
# @param [String] file_id
#   ID of the file to insert permission for.
# @param [String] value
#   User or group e-mail address, domain name or nil for 'default' type
# @param [String] perm_type
#   The value 'user', 'group', 'domain' or 'default'
# @param [String] role
#   The value 'owner', 'writer' or 'reader'
# @return [Google::APIClient::Schema::Drive::V2::Permission]
#   The inserted permission if successful, nil otherwise
def insert_permission(client, file_id, value, perm_type, role)

  drive = client.discovered_api('drive', 'v2')
  new_permission = drive.permissions.insert.request_schema.new({
    'value' => value,
    'type' => perm_type,
    'role' => role
  })
  result = client.execute(
    :api_method => drive.permissions.insert,
    :body_object => new_permission
    :parameters => { 'fileId' => file_id })
  if result.status == 200
    return result.data
  else
    puts "An error occurred: #{result.data['error']['message']}"
  end
end

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 (
  "code.google.com/p/google-api-go-client/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.

Authentication required

You need to be signed in with Google+ to do that.

Signing you in...

Google Developers needs your permission to do that.