Children: insert

Requires authorization

Inserts a file into a folder. Try it now or see an example.

Request

HTTP request

POST https://www.googleapis.com/drive/v2/files/folderId/children

Parameters

Parameter name Value Description
Path parameters
folderId string The ID of the folder.
Optional query parameters
supportsTeamDrives boolean Whether the requesting application supports Team Drives. (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

Request body

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

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

Response

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

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 child if successful, {@code null} otherwise.
   */
  private static ChildReference insertFileIntoFolder(Drive service, String folderId,
      String fileId) {
    ChildReference newChild = new ChildReference();
    newChild.setId(fileId);
    try {
      return service.children().insert(folderId, newChild).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 child, null is returned if an API error occurred</returns>
  public static ChildReference insertFileIntoFolder(DriveService service,
      String folderId, String fileId) {
    ChildReference newChild = new ChildReference();
    newChild.Id = fileId;
    try {
      return service.Children.Insert(newChild, folderId).Execute();
    } 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_Service_Drive $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_Service_Drive_ChildReference The inserted child. NULL is
 *     returned if an API error occurred.
 */
function insertFileIntoFolder($service, $folderId, $fileId) {
  $newChild = new Google_Service_Drive_ChildReference();
  $newChild->setId($fileId);
  try {
    return $service->children->insert($folderId, $newChild);
  } catch (Exception $e) {
    print "An error occurred: " . $e->getMessage();
  }
  return false;
}

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 child if successful, None otherwise.
  """
  new_child = {'id': file_id}
  try:
    return service.children().insert(
        folderId=folder_id, body=new_child).execute()
  except errors.HttpError, error:
    print 'An error occurred: %s' % error
  return None

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': fileId};
  var request = gapi.client.drive.children.insert({
    'folderId': folderId,
    'resource': body
  });
  request.execute(function(resp) { });
}

Go

Uses the Go client library.

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

// InsertFileIntoFolder adds a given file to a given folder
func InsertFileIntoFolder(d *drive.Service, folderId string, fileId string) error {
  c := &drive.ChildReference{Id: fileId}
  _, err := d.Children.Insert(folderId, c).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 (^)(GTLDriveChildReference *, NSError *))completionBlock {
  GTLDriveChildReference *newChild = [GTLDriveChildReference object];
  newChild.identifier = fileId;

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