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
addParents string Comma-separated list of parent IDs to add.
convert boolean This parameter is deprecated and has no function. (Default: false)
modifiedDateBehavior string Determines the behavior in which modifiedDate is updated. This overrides setModifiedDate.

Acceptable values are:
  • "fromBody": Set modifiedDate to the value provided in the body of the request. No change if no value was provided.
  • "fromBodyIfNeeded": Set modifiedDate to the value provided in the body of the request depending on other contents of the update.
  • "fromBodyOrNow": Set modifiedDate to the value provided in the body of the request, or to the current time if no value was provided.
  • "noChange": Maintain the previous value of modifiedDate.
  • "now": Set modifiedDate to the current time.
  • "nowIfNeeded": Set modifiedDate to the current time depending on contents of the update.
newRevision boolean Whether a blob upload should create a new revision. If false, the blob data in the current head revision is replaced. If true or not set, a new blob is created as head revision, and previous unpinned revisions are preserved for a short period of time. Pinned revisions are stored indefinitely, using additional storage quota, up to a maximum of 200 revisions. For details on how revisions are retained, see the Drive Help Center. (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 BCP 47 codes.
pinned boolean Whether to pin the new revision. A file can have a maximum of 200 pinned revisions. (Default: false)
removeParents string Comma-separated list of parent IDs to remove.
setModifiedDate boolean Whether to set the modified date using the value supplied in the request body. Setting this field to true is equivalent to modifiedDateBehavior=fromBodyOrNow, and false is equivalent to modifiedDateBehavior=now. To prevent any changes to the modified date set modifiedDateBehavior=noChange. (Default: false)
supportsTeamDrives boolean Whether the requesting application supports Team Drives. (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
https://www.googleapis.com/auth/drive.metadata

Request body

In the request body, supply the relevant portions of a Files resource, according to the rules of patch semantics, with the following properties:

Property name Value Description Notes
Optional Properties
description string A short description of the file. writable
folderColorRgb string Folder color as an RGB hex string if the file is a folder. The list of supported colors is available in the folderColorPalette field of the About resource. If an unsupported color is specified, it will be changed to the closest color in the palette. Not populated for Team Drive files. writable
indexableText.text string The text to be indexed for this file. writable
labels.restricted boolean Whether viewers and commenters are prevented from downloading, printing, and copying this file. writable
labels.starred boolean Whether this file is starred by the user. writable
labels.trashed boolean Whether this file has been trashed. This label applies to all users accessing the file; however, only owners are allowed to see and untrash files. writable
labels.viewed boolean Whether this file has been viewed by this user. writable
lastViewedByMeDate datetime Last time this file was viewed by the user (formatted RFC 3339 timestamp). writable
mimeType string The MIME type of the file. This is only mutable on update when uploading new content. This field can be left blank, and the mimetype will be determined from the uploaded content's MIME type. writable
modifiedDate datetime Last time this file was modified by anyone (formatted RFC 3339 timestamp). This is only mutable on update when the setModifiedDate parameter is set. writable
originalFilename string The original filename of the uploaded content if available, or else the original value of the title field. This is only available for files with binary content in Drive. writable
parents[] list Collection of parent folders which contain this file.

If not specified as part of an insert request, the file will be placed directly in the user's My Drive folder. If not specified as part of a copy request, the file will inherit any discoverable parents of the source file. Update requests can also use the addParents and removeParents parameters to modify the parents list.

writable
properties[] list The list of properties. writable
title string The title of this file. Note that for immutable items such as the top level folders of Team Drives, My Drive root folder, and Application Data folder the title is constant. writable
writersCanShare boolean Whether writers can share the document with other users. Not populated for Team Drive files. writable

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.Execute();

          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_Service_Drive $service Drive API service instance.
 * @param string $fileId ID of the file to rename.
 * @param string $newTitle New title for the file.
 * @return Google_Service_Drive_DriveFile The updated file. NULL is returned if
 *     an API error occurred.
 */
function renameFile($service, $fileId, $newTitle) {
  try {
    $file = new Google_Service_Drive_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

JavaScript

Uses the JavaScript client library.

/**
 * Rename a file.
 *
 * @param {String} fileId <span style="font-size: 13px; ">ID of the file to rename.</span><br> * @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.

Send feedback about...

Drive REST API v2
Drive REST API v2
Need help? Visit our support page.