Google Drive SDK

Parents: list

Requires authorization

Lists a file's parents. Try it now or see an example.

Request

HTTP request

GET 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.readonly
https://www.googleapis.com/auth/drive.metadata.readonly
https://www.googleapis.com/auth/drive.appdata

Request body

Do not supply a request body with this method.

Response

If successful, this method returns a response body with the following structure:

{
  "kind": "drive#parentList",
  "etag": etag,
  "selfLink": string,
  "items": [
    parents Resource
  ]
}
Property name Value Description Notes
kind string This is always drive#parentList.
etag etag The ETag of the list.
items[] list The actual list of parents.

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.ParentList;
import com.google.api.services.drive.model.ParentReference;

import java.io.IOException;

// ...

public class MyClass {

  // ...

  /**
   * Print a file's parents.
   *
   * @param service Drive API service instance.
   * @param fileId ID of the file to print parents for.
   */
  private static void printParents(Drive service, String fileId) {
    try {
      ParentList parents = service.parents().list(fileId).execute();

      for (ParentReference parent : parents.getItems()) {
        System.out.println("File Id: " + parent.getId());
      }
    } catch (IOException e) {
      System.out.println("An error occurred: " + e);
    }
  }

  // ...

}

.NET

Uses the .NET client library

using Google.Apis.Drive.v2;
using Google.Apis.Drive.v2.Data;

// ...

public class MyClass {

  // ...

  /// <summary>
  /// Print a file's parents.
  /// </summary>
  /// <param name="service">Drive API service instance.</param>
  /// <param name="fileId">ID of the file to print parents for</param>
  public static void PrintParents(DriveService service, String fileId) {
    ParentsResource.ListRequest request = service.Parents.List(fileId);

    try {
      ParentList parents = request.Fetch();

      foreach (ParentReference parent in parents.Items) {
        Console.WriteLine("File Id: " + parent.Id);
      }
    } catch (Exception e) {
      Console.WriteLine("An error occurred: " + e.Message);
    }
  }

  // ...

}

PHP

Uses the PHP client library

/**
 * Print a file's parents.
 *
 * @param Google_DriveService $service Drive API service instance.
 * @param String $fileId ID of the file to print parents for.
 */
function printParents($service, $fileId) {
  try {
    $parents = $service->parents->listParents($fileId);

    foreach ($parents->getItems() as $parent) {
      print 'File Id: ' . $parent->getId();
    }
  } catch (Exception $e) {
    print "An error occurred: " . $e->getMessage();
  }
}

Python

Uses the Python client library

from apiclient import errors
# ...

def print_parents(service, file_id):
  """Print a file's parents.

  Args:
    service: Drive API service instance.
    file_id: ID of the file to print parents for.
  """
  try:
    parents = service.parents().list(fileId=file_id).execute()
    for parent in parents['items']:
      print 'File Id: %s' % parent['id']
  except errors.HttpError, error:
    print 'An error occurred: %s' % error

Ruby

Uses the Ruby client library

##
# Print a file's parents.
#
# @param [Google::APIClient] client
#   Authorized client instance
# @param [String] file_id
#   ID of the file to print parents for
# @return nil
def print_parents(client, file_id)

  drive = client.discovered_api('drive', 'v2')
  result = client.execute(
    :api_method => drive.parents.list,
    :parameters => { 'fileId' => file_d })
  if api_result.status == 200
    parents = result.data
    parents.items.each do |parent|
      puts "File Id: #{parent.id}"
    end
  else
    puts "An error occurred: #{result.data['error']['message']}"
  end
end

JavaScript

Uses the JavaScript client library

/**
 * Print a file's parents.
 *
 * @param {String} fileId ID of the file to insert.
 */
function printParents(fileId) {
  var request = gapi.client.drive.parents.list({
    'fileId': fileId
  });
  request.execute(function(resp) {
    for (parent in resp.items) {
      console.log('File Id: ' + resp.items[parent].id);
    }
  });
}

Go

Uses the Go client library

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

// PrintParents displays the parents of a given file
func PrintParents(d *drive.Service, fileId string) error {
  r, err := d.Parents.List(fileId).Do()
  if err != nil {
    fmt.Printf("An error occurred: %v\n", err)
    return err
  }
  for _, p := range r.Items {
    fmt.Printf("Folder with ID: %v", p.Id)
  }
  return nil
}

Objective-C

Uses the Objective-C client library

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

+ (void)printFilesInFolderWithService:(GTLServiceDrive *)service
                               fileId:(NSString *)fileId {
  GTLQueryDrive *query = [GTLQueryDrive queryForParentsListWithFileId:fileId];
  // queryTicket can be used to track the status of the request.
  GTLServiceTicket *queryTicket =
    [service executeQuery:query
        completionHandler:^(GTLServiceTicket *ticket,
                            GTLDriveParentList *parents, NSError *error) {
          if (error == nil) {
            for (GTLDriveParentReference *parent in parents) {
              NSLog(@"File Id: %@", parent.identifier);
            }
          } else {
            NSLog(@"An error occurred: %@", 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.