如何用Google Drive API V3通过共享链接获取目录及子目录数据?
Great question! When someone shares a Drive directory with your email, you can absolutely access its contents (and nested subdirectories) using the Drive API v3—you just need to tweak your approach slightly from working with a known directory ID. Here's a step-by-step breakdown:
1. Extract the Directory ID from the Share Link
First, pull the unique directory ID out of the shared link. Most Google Drive share links follow this structure:
https://drive.google.com/drive/folders/
YOUR_SHARED_DIR_ID?usp=sharing
The string between folders/ and the first ? is your target directory ID. For example, in https://drive.google.com/drive/folders/123abcXYZ?usp=sharing, the ID is 123abcXYZ.
2. Adjust Your API Request for Shared Resources
Your core request structure stays similar, but you need two critical parameters to handle content from another user's drive:
supportsAllDrives=true: Informs the API you're accessing resources outside your own primary driveincludeItemsFromAllDrives=true: Ensures shared items are included in the response
Example Request
Request URL:
GET https://www.googleapis.com/drive/v3/files?q="YOUR_SHARED_DIR_ID"+in+parents&includeItemsFromAllDrives=true&supportsAllDrives=true&fields=nextPageToken,files(id,name,mimeType,parents)
Headers:
Authorization: Bearer YOUR_ACCESS_TOKEN
- The
fieldsparameter lets you specify which file properties to return (customize this based on your needs). - Use
nextPageTokento paginate through large file sets, just like you would with your own directories.
3. Recursively Fetch Subdirectories
To get content from nested subdirectories, implement a recursive workflow:
- When you receive a file list, filter for items where
mimeTypeequalsapplication/vnd.google-apps.folder(these are subdirectories). - For each subdirectory ID, repeat the API request above (using the subdirectory ID in the
qparameter'sparentsclause). - Continue this process until you've traversed all nested folders.
Are There Alternatives to Using the Directory ID?
Unfortunately, the Drive API doesn't support directly passing a share link as a parameter—all resource operations rely on the unique ID. That said, if the shared directory is publicly accessible (anyone with the link can view it), you could use an API key instead of an OAuth 2.0 token. But for directories restricted to your email, you'll still need a valid Bearer token with appropriate scopes (like drive.readonly or drive).
Key Notes
- Ensure your OAuth token has the correct scopes: For read access,
https://www.googleapis.com/auth/drive.readonlyis sufficient. - If you get a 403 "Permission Denied" error, double-check that the shared directory was actually shared with the email linked to your OAuth token, and that your token's scopes include Drive access.
内容的提问来源于stack exchange,提问作者Sourabh Bhutani

