Google Drive SDK

Parents: get

Requires authorization

Gets a specific parent reference. Try it now or see an example.

Request

HTTP request

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

Parameters

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

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 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.client.http.HttpResponseException;
import com.google.api.services.drive.Drive;

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

public class MyClass {

  // ...

  /**
   * Check if a file is in a specific folder
   *
   * @param service Drive API service instance.
   * @param folderId ID of the folder.
   * @param fileId ID of the file.
   * @return Whether or not the file is in the folder.
   */
  private static boolean isFileInFolder(Drive service, String folderId,
      String fileId) throws IOException {
    try {
      service.parents().get(fileId, folderId).execute();
    } catch (HttpResponseException e) {
      if (e.getStatusCode() == 404) {
        return false;
      } else {
        System.out.println("An error occured: " + e);
        throw e;
      }
    } catch (IOException e) {
      System.out.println("An error occured: " + e);
      throw e;
    }
    return true;
  }

  // ...

}

.NET

Uses the .NET client library

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

using System.Net;
// ...

public class MyClass {

  // ...

  /// <summary>
  /// Check if a file is in a specific folder.
  /// </summary>
  /// <param name="service">Drive API service instance.</param>
  /// <param name="folderId">ID of the folder.</param>
  /// <param name="fileId">ID of the file.</param>
  /// <returns>Whether or not the file is in the folder</returns>
  public static bool IsFileInFolder(DriveService service, String folderId, String fileId) {
    try {
      service.Parents.Get(fileId, folderId).Fetch();
    } catch (GoogleApiRequestException e) {
      if (e.HttpStatusCode == HttpStatusCode.NotFound) {
        return false;
      } else {
        throw;
      }
    } catch (Exception e) {
      Console.WriteLine("An error occurred: " + e.Message);
      throw;
    }
    return true;
  }

  // ...

}

PHP

Uses the PHP client library

/**
 * Check if a file is in a specific folder.
 *
 * @param Google_DriveService $service Drive API service instance.
 * @param String $folderId ID of the folder.
 * @param String $fileId ID of the file.
 * @return boolean Whether or not the file is in the folder.
 */
function isFileInFolder($service, $folderId, $fileId) {
  try {
    $service->parents->get($fileId, $folderId);
  } catch (apiServiceException $e) {
    if ($e->getCode() == 404) {
      return false;
    } else {
      print "An error occurred: " . $e->getMessage();
      throw $e;
    }
  } catch (Exception $e) {
    print "An error occurred: " . $e->getMessage();
    throw $e;
  }
  return true;
}

Python

Uses the Python client library

from apiclient import errors
# ...

def is_file_in_folder(service, folder_id, file_id):
  """Check if a file is in a specific folder.

  Args:
    service: Drive API service instance.
    folder_id: ID of the folder.
    file_id: ID of the file.
  Returns:
    Whether or not the file is in the folder.
  """
  try:
    service.parents().get(fileId=file_id, parentId=folder_id).execute()
  except errors.HttpError, error:
    if error.resp.status == 404:
      return False
    else:
      print 'An error occurred: %s' % error
      raise error
  return True

Ruby

Uses the Ruby client library

##
# Check if a file is in a specific folder
#
# @param [Google::APIClient] client
#   Authorized client instance
# @param [String] folder_id
#   ID of the folder
# @param [String] file_id
#   ID of the file
# @return [boolean]
#   Whether or not the file is in the folder
def is_file_in_folder(client, folder_id, file_id)

  drive = client.discovered_api('drive', 'v2')
  result = client.execute(
    :api_method => drive.parents.get,
    :parameters => {
      'fileId' => file_id,
      'parentId' => folder_id })
  if result.status == 200
    return true
  elsif result.status == 404
    return false
  else
    puts "An error occurred: #{result.data['error']['message']}"
  end
end

JavaScript

Uses the JavaScript client library

/**
 * Check if a file is in a specific folder.
 *
 * @param {String} folderId ID of the folder.
 * @param {String} fileId ID of the file.
 * @param {Function} callback Function to call when the request is complete.
 */
function isFileInFolder(folderId, fileId, callback) {
  var request = gapi.client.drive.parents.get({
    'parentId': folderId,
    'fileId': fileId
  });
  request.execute(function(resp) {
    if (resp.error) {
      if (resp.error.code = 404) {
        callback(false);
      } else {
        console.log('An error occurred: ' + resp.error.message);
        callback(null);
      }
    } else {
      callback(true);
    }
  });
}

Go

Uses the Go client library

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


// IsFileChild tests whether the given file is in the given folder
func IsFileChild(d *drive.Service, folderId string,
    fileId string) (bool, error) {
  _, err := d.Parents.Get(fileId, folderId).Do()
  if err != nil {
    fmt.Printf("An error occurred: %v\n", err)
    return false, err
  }
  return true, nil
}

Objective-C

Uses the Objective-C client library

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

+ (void)checkIfFileIsInFolderWithService:(GTLServiceDrive *)service
                                folderId:(NSString *)folderId
                                  fileId:(NSString *)fileId
                         completionBlock:(void (^)(BOOL, NSError *))completionBlock {
  GTLQueryDrive *query =
    [GTLQueryDrive queryForParentsGetWithFileId:fileId parentId:folderId];
  // 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(YES, nil);
          } else {
            if ([error code] == 404) {
              completionBlock(NO, nil);
            } 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.