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

  1. A public Google Drive folder (make sure it’s set to “Anyone with the link can view”)
  2. Google Cloud Project with the Drive API enabled
  3. API key from Google Cloud Console

Setting Up

First, you need to set up a Google Cloud project and enable the Drive API:

  1. Go to the Google Cloud Console
  2. Create a new project or select an existing one
  3. Enable the Google Drive API
  4. Create an API key under “Credentials”

Python Implementation

Here’s a Python script that lists files in a public Google Drive folder:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import requests

def list_public_drive_folder(folder_id, api_key):
    """
    List files in a public Google Drive folder
    
    Args:
        folder_id (str): The ID of the public Google Drive folder
        api_key (str): Your Google API key
    
    Returns:
        list: List of file information dictionaries
    """
    # Base URL for Google Drive API
    url = "https://www.googleapis.com/drive/v3/files"
    
    # Parameters for the API request
    params = {
        'q': f"'{folder_id}' in parents and trashed=false",
        'key': api_key,
        'fields': 'files(id, name, mimeType, size, modifiedTime)'
    }
    
    try:
        response = requests.get(url, params=params)
        response.raise_for_status()
        data = response.json()
        return data.get('files', [])
    except requests.exceptions.RequestException as e:
        print(f"Error making API request: {e}")
        return []

def main():
    # Replace these with your actual values
    FOLDER_ID = "your_public_folder_id_here"  # Found in the folder URL
    API_KEY = "your_google_api_key_here"
    
    files = list_public_drive_folder(FOLDER_ID, API_KEY)
    
    if files:
        print(f"Found {len(files)} files in the folder:")
        for file in files:
            print(f"- {file['name']} (ID: {file['id']}, Type: {file['mimeType']})")
    else:
        print("No files found or error occurred.")

if __name__ == "__main__":
    main()

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:

1
https://drive.google.com/drive/folders/1ABC123def456GHI789jkl

In this example, 1ABC123def456GHI789jkl is the folder ID.

Installing Dependencies

You’ll need to install the requests library if you haven’t already:

1
pip install requests

Understanding the Code

  1. API Endpoint: We use the Google Drive v3 API files endpoint
  2. Query Parameter: The q parameter uses a query to filter files:
    • '{folder_id}' in parents - Only files in our target folder
    • trashed=false - Exclude files in trash
  3. Fields: We specify which file properties to return to minimize data transfer
  4. 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 ID
  • name: The filename
  • mimeType: 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:

1
2
3
4
5
6
7
8
9
import os
import requests

def list_public_drive_folder_env(folder_id):
    api_key = os.getenv('GOOGLE_API_KEY')
    if not api_key:
        raise ValueError("GOOGLE_API_KEY environment variable not set")
    
    return list_public_drive_folder(folder_id, api_key)

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.