How to move files and folders using google drive API?

Drive API V3 has this:

Moving files between folders

To add or remove parents for an existing file, use the addParents and removeParents query parameters on the files.update method.

Both parameters may be used to move a file from one folder to another: https://developers.google.com/drive/v3/web/folder#inserting_a_file_in_a_folder


Here is the one step method to move file to the new folder using Patch and the PHP client library:

/**
 * Move a file.
 *
 * @param Google_Service_Drive_DriveFile $service Drive API service instance.
 * @param string $fileId ID of the file to move.
 * @param string $newParentId Id of the folder to move to.
 * @return Google_Service_Drive_DriveFile The updated file. NULL is returned if an API error occurred.
 */
function moveFile($service, $fileId, $newParentId) {
  try {
    $file = new Google_Service_Drive_DriveFile();

    $parent = new Google_Service_Drive_ParentReference();
    $parent->setId($newParentId);

    $file->setParents(array($parent));

    $updatedFile = $service->files->patch($fileId, $file);

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

Update: If you want to use Drive API v3, use below code documented here:

/**
 * Move a file.
 *
 * @param Google_Service_Drive_DriveFile $service Drive API service instance.
 * @param string $fileId ID of the file to move.
 * @param string $newParentId Id of the folder to move to.
 * @return Google_Service_Drive_DriveFile The updated file. NULL is returned if an API error occurred.
 */
function moveFile($service, $fileId, $newParentId) {
  try {

    $emptyFileMetadata = new Google_Service_Drive_DriveFile();
    // Retrieve the existing parents to remove
    $file = $service->files->get($fileId, array('fields' => 'parents'));
    $previousParents = join(',', $file->parents);
    // Move the file to the new folder
    $file = $service->files->update($fileId, $emptyFileMetadata, array(
      'addParents' => $newParentId,
      'removeParents' => $previousParents,
      'fields' => 'id, parents'));

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

To move FILE-A from FOLDER-1 to FOLDER-2, you can use the delete and add calls at https://developers.google.com/drive/v2/reference/parents to remove FOLDER-1 as a parent and add FOLDER-2.

You can also do a Patch on the file with the updated parents array.