Google Drive SDK

Files: patch

Requires authorization

Updates file metadata. This method supports patch semantics. Try it now or see an example.


Request

HTTP request

PATCH https://www.googleapis.com/drive/v2/files/fileId

Parameters

Parameter name Value Description
Path parameters
fileId string The ID of the file to update.
Optional query parameters
convert boolean Whether to convert this file to the corresponding Google Docs format. (Default: false)
newRevision boolean Whether a blob upload should create a new revision. If false, the blob data in the current head revision is replaced. If not set or true, a new blob is created as head revision, and previous revisions are preserved (causing increased use of the user's data storage quota). (Default: true)
ocr boolean Whether to attempt OCR on .jpg, .png, .gif, or .pdf uploads. (Default: false)
ocrLanguage string If ocr is true, hints at the language to use. Valid values are ISO 639-1 codes.
pinned boolean Whether to pin the new revision. (Default: false)
setModifiedDate boolean Whether to set the modified date with the supplied modified date. (Default: false)
timedTextLanguage string The language of the timed text.
timedTextTrackName string The timed text track name.
updateViewedDate boolean Whether to update the view date after successfully updating the file. (Default: true)
useContentAsIndexableText boolean Whether to use the content as indexable text. (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
https://www.googleapis.com/auth/drive.appdata
https://www.googleapis.com/auth/drive.scripts
https://www.googleapis.com/auth/drive.apps.readonly

Request body

In the request body, supply a Files resource.

Response

If successful, this method returns a Files 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.Drive.Files;
import com.google.api.services.drive.model.File;

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

public class MyClass {

  // ...

  /**
   * Rename a file.
   *
   * @param service Drive API service instance.
   * @param fileId ID of the file to rename.
   * @param newTitle New title for the file.
   * @return Updated file metadata if successful, {@code null} otherwise.
   */
  private static File renameFile(Drive service, String fileId, String newTitle) {
    try {
      File file = new File();
      file.setTitle(newTitle);

      // Rename the file.
      Files.Patch patchRequest = service.files().patch(fileId, file);
      patchRequest.setFields("title");

      File updatedFile = patchRequest.execute();
      return updatedFile;
    } 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;

// ...

public class MyClass {

  // ...

  /// <summary>
  /// Rename a file.
  /// </summary>
  /// <param name="service">Drive API service instance.</param>
  /// <param name="fileId">ID of the file to rename.</param>
  /// <param name="newTitle">New title for the file.</param>
  /// <returns>Updated file metadata, null is returned if an API error occurred.</returns>
  private static File renameFile(DriveService service, String fileId, String newTitle) {
      try {
          File file = new File();
          file.Title = newTitle;

          // Rename the file.
          FilesResource.PatchRequest request = service.Files.Patch(file, fileId);
          File updatedFile = request.Fetch();

          return updatedFile;
      } catch (Exception e) {
          Console.WriteLine("An error occurred: " + e.Message);
          return null;
      }
  }

  //...

}

PHP

Uses the PHP client library

/**
 * Rename a file.
 *
 * @param Google_DriveService $service Drive API service instance.
 * @param string $fileId ID of the file to rename.
 * @param string $newTitle New title for the file.
 * @return Google_DriveFile The updated file. NULL is returned if an API error occurred.
 */
function renameFile($service, $fileId, $newTitle) {
  try {
    $file = new Google_DriveFile();
    $file->setTitle($newTitle);

    $updatedFile = $service->files->patch($fileId, $file, array(
      'fields' => 'title'
    ));

    return $updatedFile;
  } catch (Exception $e) {
    print "An error occurred: " . $e->getMessage();
  }
}

Python

Uses the Python client library

from apiclient import errors
# ...

def rename_file(service, file_id, new_title):
  """Rename a file.

  Args:
    service: Drive API service instance.
    file_id: ID of the file to rename.
    new_title: New title for the file.
  Returns:
    Updated file metadata if successful, None otherwise.
  """
  try:
    file = {'title': new_title}

    # Rename the file.
    updated_file = service.files().patch(
        fileId=file_id,
        body=file,
        fields='title').execute()

    return updated_file
  except errors.HttpError, error:
    print 'An error occurred: %s' % error
    return None

Ruby

Uses the Ruby client library

##
# Rename a file
#
# @param [Google::APIClient] client
#   Authorized client instance
# @param [String] file_id
#   ID of file to update
# @param [String] title
#   New title of file
# @return [Google::APIClient::Schema::Drive::V2::File]
#   File if update, nil otherwise
def rename_file(client, file_id, title)
  drive = client.discovered_api('drive', 'v2')
  result = client.execute(
    :api_method => drive.files.patch,
    :body_object => { 'title' => title },
    :parameters => { 'fileId' => file_id })
  if result.status == 200
    return result.data
  end
  puts "An error occurred: #{result.data['error']['message']}"
  return nil
end

JavaScript

Uses the JavaScript client library

/**
 * Rename a file.
 *
 * @param {String} fileId ID of the file to rename.
* @param {String} newTitle New title for the file. */ function renameFile(fileId, newTitle) { var body = {'title': newTitle}; var request = gapi.client.drive.files.patch({ 'fileId': fileId, 'resource': body }); request.execute(function(resp) { console.log('New Title: ' + resp.title); }); }

Go

Uses the Go client library

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

// RenameFile renames a given file to a given title
func RenameFile(d *drive.Service, fileId string,
    title string) (*drive.File, error) {
  f := &drive.File{Title: title}
  r, err := d.Files.Patch(fileId, f).Do()
  if err != nil {
    fmt.Printf("An error occurred: %v\n", err)
    return nil, err
  }
  return r, nil
}

Objective-C

Uses the Objective-C client library

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

+ (void)renameFileWithService:(GTLServiceDrive *)service
                       fileId:(NSString *)fileId
                     newTitle:(NSString *)newTitle
              completionBlock:(void (^)(GTLDriveFile *, NSError *))completionBlock {
  GTLDriveFile *file = [GTLDriveFile object];
  file.title = newTitle;

  GTLQueryDrive *query = [GTLQueryDrive queryForFilesPatchWithObject:file
                                                              fileId:fileId];
  // queryTicket can be used to track the status of the request.
  GTLServiceTicket *queryTicket =
    [service executeQuery:query
        completionHandler:^(GTLServiceTicket *ticket, GTLDriveFile *updatedFile,
                            NSError *error) {
        if (error == nil) {
          completionBlock(updatedFile, 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.