Find file's parent id : Google Drive API V3

18,681

Solution 1

If you have the file id of the file in question then Files: get you need to add fields ie parents along with the file id.

Request

GET https://www.googleapis.com/drive/v3/files/0B5pJkOVaKccENWNNcFFaU2lSM0E?fields=parents&key={YOUR_API_KEY}

Returns

{ "parents": [ "0B5pJkOVaKccEYW5lVHBKd1Zwc28" ] }

The result is actually a file id. Remember files and directories are the same in Drive.

Do files.get again

GET https://www.googleapis.com/drive/v3/files/0B5pJkOVaKccEYW5lVHBKd1Zwc28?key={YOUR_API_KEY}

Results

{ "kind": "drive#file", "id": "0B5pJkOVaKccEYW5lVHBKd1Zwc28", "name": "SiteBackups", "mimeType": "application/vnd.google-apps.folder" }

Solution 2

Congrats, you found the Google Drive API version 3 several hours before we officially announced it. :)

In v3, there is no longer a parents collection. Instead, you get the parents property by doing a files.get with the child's ID. Ideally, you would use the fields parameter to restrict the response to just the parent(s). Note: A file may have more than one parent, so be prepared to handle multiple parents.

You can get a sense of the changes from v2 to v3 by looking at the migration cheat sheet.

Solution 3

If you are using the SDK to do it

        $service    = new Google_Service_Drive($client);

        // Print the names and IDs.
        $optParams = array(
            'fields'    => 'nextPageToken, files(id, name, fileExtension, trashed, webViewLink, mimeType, ownedByMe, parents, fileExtension, webContentLink)',
            'q'         => $folderId . " in parents" // pass the folder id as a string to the variable $folderId
        );

        $results = $service->files->listFiles($optParams);
        $results = $results->getFiles();
Share:
18,681
akgaur
Author by

akgaur

Updated on June 09, 2022

Comments

  • akgaur
    akgaur almost 2 years

    enter image description here

    Today after I updated my Drive API to V3, I dint find any method to find the parent of the selected file . Is the rest endpoint to fetch json related to parent's info changed?