Google Drive SDK

Permissions: update

Requires authorization

Updates a permission. 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

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

Parameters

Parameter name Value Description
Path parameters
fileId string The ID for the file.
permissionId string The ID for the permission.
Optional query parameters
transferOwnership boolean Whether changing a role to 'owner' should also downgrade the current owners to writers. (Default: false)

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
Optional Properties
additionalRoles[] list Additional roles for this user. Only commenter is currently allowed. writable
role string The primary role for this user. Allowed values are:
  • owner
  • reader
  • writer


Acceptable values are:
  • "owner":
  • "reader":
  • "writer":
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 {

  // ...

  /**
   * Update a permission's role.
   *
   * @param service Drive API service instance.
   * @param fileId ID of the file to update permission for.
   * @param permissionId ID of the permission to update.
   * @param newRole The value "owner", "writer" or "reader".
   * @return The updated permission if successful, {@code null} otherwise.
   */
  private static Permission updatePermission(Drive service, String fileId,
      String permissionId, String newRole) {
    try {
      // First retrieve the permission from the API.
      Permission permission = service.permissions().get(
          fileId, permissionId).execute();
      permission.setRole(newRole);
      return service.permissions().update(
          fileId, permissionId, permission).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>
  /// Update a permission's role.
  /// </summary>
  /// <param name="service">Drive API service instance.</param>
  /// <param name="fileId">ID of the file to update permission for.</param>
  /// <param name="permissionId">ID of the permission to update.</param>
  /// <param name="newRole">The value "owner", "writer" or "reader".</param>
  /// <returns>The updated permission, null is returned if an API error occurred</returns>
  public static Permission UpdatePermission(DriveService service, String fileId,
      String permissionId, String newRole) {
    try {
      // First retrieve the permission from the API.
      Permission permission = service.Permissions.Get(fileId, permissionId).Fetch();
      permission.Role = newRole;
      return service.Permissions.Update(permission, fileId, permissionId).Fetch();
    } catch (Exception e) {
      Console.WriteLine("An error occurred: " + e.Message);
    }
    return null;
  }

  // ...

}

PHP

Uses the PHP client library

/**
 * Update a permission's role.
 *
 * @param Google_DriveService $service Drive API service instance.
 * @param String $fileId ID of the file to update permission for.
 * @param String $permissionId ID of the permission to update.
 * @param String $newRole The value "owner", "writer" or "reader".
 * @return Google_Permission The updated permission. NULL is returned if an API error occurred.
 */
function updatePermission($service, $fileId, $permissionId, $newRole) {
  try {
    // First retrieve the permission from the API.
    $permission = $service->permissions->get($fileId, $permissionId);
    $permission->setRole($newRole);
    return $service->permissions->update($fileId, $permissionId, $permission);
  } catch (Exception $e) {
    print "An error occurred: " . $e->getMessage();
  }
  return NULL;
}

Python

Uses the Python client library

from apiclient import errors
# ...

def update_permission(service, file_id, permission_id, new_role):
  """Update a permission's role.

  Args:
    service: Drive API service instance.
    file_id: ID of the file to update permission for.
    permission_id: ID of the permission to update.
    new_role: The value 'owner', 'writer' or 'reader'.

  Returns:
    The updated permission if successful, None otherwise.
  """
  try:
    # First retrieve the permission from the API.
    permission = service.permissions().get(
        fileId=file_id, permissionId=permission_id).execute()
    permission['role'] = new_role
    return service.permissions().update(
        fileId=file_id, permissionId=permission_id, body=permission).execute()
  except errors.HttpError, error:
    print 'An error occurred: %s' % error
  return None

Ruby

Uses the Ruby client library

##
# Update a permission's role
#
# @param [Google::APIClient] client
#   Authorized client instance
# @param [String] file_id
#   ID of the file to update permission for
# @param [String] permission_id
#   ID of the permission to update
# @param [String] new_role
#   The value 'owner', 'writer' or 'reader'
# @return [Google::APIClient::Schema::Drive::V2::Permission]
#   The updated permission if successful, nil otherwise
def update_permission(client, file_id, permission_id, new_role)

  drive = client.discovered_api('drive', 'v2')# First retrieve the permission from the API.
  result = client.execute(
    :api_method => drive.permissions.get,
    :parameters => {
      'fileId' => file_id,
      'permissionId' => permission_id
    })
  if result.status == 200
    permission = result.data
    permission.role = new_role
    result = client.execute(
      :api_method => drive.permissions.update,
      :body_object => updated_permission,
      :parameters => {
        'fileId' => file_id,
        'permissionId' => permission_id
      })
    if result.status == 200
      return result.data
    end
  end
  puts "An error occurred: #{result.data['error']['message']}"
end

JavaScript

Uses the JavaScript client library

/**
 * Update a permission's role.
 *
 * @param {String} fileId ID of the file to update permission for.
 * @param {String} permissionId ID of the permission to update.
 * @param {String} newRole The value "owner", "writer" or "reader".
 */
function updatePermission(fileId, permissionId, newRole) {
  // First retrieve the permission from the API.
  var request = gapi.client.drive.permissions.get({
    'fileId': fileId,
    'permissionId': permissionId
  });
  request.execute(function(resp) {
    resp.role = newRole;
    var updateRequest = gapi.client.drive.permissions.update({
      'fileId': fileId,
      'permissionId': permissionId,
      'resource': resp
    });
    updateRequest.execute(function(resp) { });
  });
}

Go

Uses the Go client library

import (
  "code.google.com/p/google-api-go-client/drive/v2"
  "fmt"
)


// UpdatePermission fetches and updates a permission to the given role
func UpdatePermission(d *drive.Service, fileId string, permissionId string,
    role string) error {
  p, err := d.Permissions.Get(fileId, permissionId).Do()
  if err != nil {
    fmt.Printf("An error occurred: %v\n", err)
    return err
  }
  p.Role = role
  _, err = d.Permissions.Update(fileId, permissionId, 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)updatePermissionWithService:(GTLServiceDrive *)service
                             fileId:(NSString *)fileId
                       permissionId:(NSString *)permissionId
                            newRole:(NSString *)newRole
                    completionBlock:(void (^)(GTLDrivePermission *, NSError *))completionBlock {
  GTLQueryDrive *getQuery =
    [GTLQueryDrive queryForPermissionsGetWithFileId:fileId
                                       permissionId:permissionId];
  // queryTicket can be used to track the status of the request.
  GTLServiceTicket *getQueryTicket =
    [service executeQuery:getQuery
        completionHandler:^(GTLServiceTicket *ticket,
                            GTLDrivePermission *permission, NSError *error) {
          if (error == nil) {
            permission.role = newRole;
            GTLQueryDrive *updateQuery =
              [GTLQueryDrive queryForPermissionsUpdateWithObject:permission
                                                          fileId:fileId
                                                    permissionId:permissionId];
            // queryTicket can be used to track the status of the request.
            GTLServiceTicket *updateQueryTicket =
              [service executeQuery:updateQuery
                  completionHandler:^(GTLServiceTicket *ticket,
                                      GTLDrivePermission *permission, NSError *error) {
                    if (error == nil) {
                      completionBlock(permission, nil);
                    } else {
                      NSLog(@"An error occurred: %@", error);
                      completionBlock(nil, error);
                    }
                  }];
          } 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.