How to list files in shortcut folder in GDrive v3

1k views Asked by At

I am trying to use the GDrive API v3 to list all files and folders in a shortcut folder.

When using the API I am able to list all files using the following request:

curl \
  'https://www.googleapis.com/drive/v3/files?q=%27root%27%20in%20parents&supportsAllDrives=true&supportsTeamDrives=true&key=[YOUR_API_KEY]' \
  --header 'Authorization: Bearer [YOUR_ACCESS_TOKEN]' \
  --header 'Accept: application/json' \
  --compressed

Which returns something like:

{
    "kind": "drive#file",
    "id": "xxxxxxxxxxxxxx",
    "name": "Name of file here",
    "mimeType": "application/vnd.google-apps.shortcut"
}

When I take that id, and use it in the same request above, which works for "mimeType": "application/vnd.google-apps.folder". I get an empty payload:

{
 "kind": "drive#fileList",
 "incompleteSearch": false,
 "files": []
}

Am I using the wrong endpoint? Is there something else I need to add to the API request?

2

There are 2 answers

2
iansedano On BEST ANSWER

The shortcut item in your Drive has an attribute with the id of the actual folder.

If for example, you have only one shortcut to a folder in your Drive when you make the request you will get two results when listing all files in root.

  1. one with mime type "shortcut" - which is the shortcut.
  2. one with mime type "folder" - seems that the API lists this anyway.

If for any reason you only get the shortcut, you can get the details of the shortcut:

Request

curl \
  'https://www.googleapis.com/drive/v3/files/[YOUR_SHORTCUT_ID]?fields=*&key=[YOUR_API_KEY]' \
  --header 'Authorization: Bearer [YOUR_ACCESS_TOKEN]' \
  --header 'Accept: application/json' \
  --compressed

Response

(I have removed most of the fields from the response)

{
 "kind": "drive#file",
 "id": "[YOUR_SHORTCUT_ID]",
 "name": "[YOUR_SHORTCUT_NAME]",
 "mimeType": "application/vnd.google-apps.shortcut",
 "starred": false,
 "trashed": false,
 "shortcutDetails": {
  "targetId": "[THE_ACTUAL_FOLDER_ID]",
  "targetMimeType": "application/vnd.google-apps.folder"
 }
}

Within shortcutDetails is the targetId.

After which, you can write your original request with the proper "ID" in parents.

Reference

0
pinoyyid On

The shortcut is not synonymous with the directory it points to. You will need to make two requests, one to get the target ID ("targetId") from the shortcut and then a second call to find files with targetId in parents.