Google Drive SDK

Parents: insert

Requires authorization

Adds a parent folder for a file. Try it now or see an example.

Request

HTTP request

POST https://www.googleapis.com/drive/v2/files/fileId/parents

Parameters

Parameter name Value Description
Path parameters
fileId string The ID of the file.

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

Request body

In the request body, supply a Parents resource with the following properties:

Property name Value Description Notes
Required Properties
id string The ID of the parent.

Response

If successful, this method returns a Parents 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.ParentReference;

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

public class MyClass {

  // ...

  /**
   * Insert a file into a folder.
   *
   * @param service Drive API service instance.
   * @param folderId ID of the folder to insert the file into
   * @param fileId ID of the file to insert.
   * @return The inserted parent if successful, {@code null} otherwise.
   */
  private static ParentReference insertFileIntoFolder(Drive service, String folderId,
      String fileId) {
    ParentReference newParent = new ParentReference();
    newParent.setId(folderId);
    try {
      return service.parents().insert(fileId, newParent).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 file into a folder.
  /// </summary>
  /// <param name="service">Drive API service instance.</param>
  /// <param name="folderId">ID of the folder to insert the file into.</param>
  /// <param name="fileId">ID of the file to insert.</param>
  /// <returns>The inserted parent, null is returned if an API error occurred</returns>
  public static ParentReference insertFileIntoFolder(DriveService service, String folderId,
      String fileId) {
    ParentReference newParent = new ParentReference();
    newParent.Id = folderId;
    try {
      return service.Parents.Insert(newParent, fileId).Fetch();
    } catch (Exception e) {
      Console.WriteLine("An error occurred: " + e.Message);
    }
    return null;
  }

  // ...

}

PHP

Uses the PHP client library

/**
 * Insert a file into a folder.
 *
 * @param Google_DriveService $service Drive API service instance.
 * @param String $folderId ID of the folder to insert the file into.
 * @param String $fileId ID of the file to insert.
 * @return Google_ParentReference The inserted parent. NULL is returned if an API error occurred.
 */
function insertFileIntoFolder($service, $folderId, $fileId) {
  $newParent = new Google_ParentReference();
  $newParent->setId($folderId);
  try {
    return $service->parents->insert($fileId, $newParent);
  } catch (Exception $e) {
    print "An error occurred: " . $e->getMessage();
  }
  return NULL;
}

Python

Uses the Python client library

from apiclient import errors
# ...

def insert_file_into_folder(service, folder_id, file_id):
  """Insert a file into a folder.

  Args:
    service: Drive API service instance.
    folder_id: ID of the folder to insert the file into.
    file_id: ID of the file to insert.
  Returns:
    The inserted parent if successful, None otherwise.
  """
  new_parent = {'id': folder_id}
  try:
    return service.parents().insert(
        fileId=file_id, body=new_parent).execute()
  except errors.HttpError, error:
    print 'An error occurred: %s' % error
  return None

Ruby

Uses the Ruby client library

##
# Insert a file into a folder
#
# @param [Google::APIClient] client
#   Authorized client instance
# @param [String] folder_id
#   ID of the folder to insert the file into
# @param [String] file_id
#   ID of the file to insert
# @return [Google::APIClient::Schema::Drive::V2::ParentReference]
#   The inserted parent if successful, nil otherwise
def insert_file_into_folder(client, folder_id, file_id)

  drive = client.discovered_api('drive', 'v2')
  new_parent = drive.parents.insert.request_schema.new({
    'id' => folder_id
  })
  result = client.execute(
    :api_method => drive.parents.insert,
    :body_object => new_parent,
    :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 file into a folder.
 *
 * @param {String} folderId ID of the folder to insert the file into.
 * @param {String} fileId ID of the file to insert.
 */
function insertFileIntoFolder(folderId, fileId) {
  var body = {'id': folderId};
  var request = gapi.client.drive.parents.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"
)


// AddParentToFile adds a given file to a given folder
func AddParentToFile(d *drive.Service, folderId string, fileId string) error {
  p := &drive.ParentReference{Id: folderId}
  _, err := d.Parents.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)insertFileInFolderWithService:(GTLServiceDrive *)service
                             folderId:(NSString *)folderId
                               fileId:(NSString *)fileId
                      completionBlock:(void (^)(GTLDriveParentReference *, NSError *))completionBlock {
  GTLDriveParentReference *newParent = [GTLDriveParentReference object];
  newParent.identifier = folderId;

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