When you have a Google Drive folder that’s shared publicly (set to “Anyone with the link can view”), you can access its contents programmatically using the Google Drive API. This is useful for building applications that need to display or process files from a shared drive.
Prerequisites
- A public Google Drive folder (make sure it’s set to “Anyone with the link can view”)
- Google Cloud Project with the Drive API enabled
- API key from Google Cloud Console
Setting Up
First, you need to set up a Google Cloud project and enable the Drive API:
- Go to the Google Cloud Console
- Create a new project or select an existing one
- Enable the Google Drive API
- Create an API key under “Credentials”
Python Implementation
Here’s a Python script that lists files in a public Google Drive folder:
|
|
How to Get the Folder ID
The folder ID can be found in the URL when you open the Google Drive folder in your browser:
|
|
In this example, 1ABC123def456GHI789jkl is the folder ID.
Installing Dependencies
You’ll need to install the requests library if you haven’t already:
|
|
Understanding the Code
- API Endpoint: We use the Google Drive v3 API files endpoint
- Query Parameter: The
qparameter uses a query to filter files:'{folder_id}' in parents- Only files in our target foldertrashed=false- Exclude files in trash
- Fields: We specify which file properties to return to minimize data transfer
- Error Handling: Basic error handling for network issues
File Information Returned
The script returns information about each file including:
id: The unique Google Drive file IDname: The filenamemimeType: The file type (e.g., ‘application/pdf’, ‘image/jpeg’)size: File size in bytes (if available)modifiedTime: Last modification timestamp
We could also have used webViewLink for instance to get the links for each doc in the folder.
Security Considerations
- Keep your API key secure and never commit it to version control
- Consider using environment variables for sensitive information
- The API key should be restricted to only the Drive API in Google Cloud Console
- For additional security, you can restrict the API key by IP address if your server has a static IP
Example with Environment Variables
For better security, use environment variables:
|
|
Conclusion
Listing contents of a public Google Drive folder is straightforward with the Drive API. This approach works without OAuth authentication because the folder is publicly accessible. Remember that this method only works for folders that are explicitly shared publicly - it won’t work for folders that require individual user authentication.
This technique can be extended to build more complex applications like file downloaders, content management systems, or automated backup solutions that interact with Google Drive.