Google Drive connector
Read files recursively from Google Drive folders, via a service account or a personal account signed in with OAuth. Supports MIME-type filtering and auto-exports Google Docs, Sheets, and Slides to text or CSV.
The google_drive connector provides utilities for reading files from Google Drive, authenticated with a service account or with a personal Google account signed in through OAuth.
from cocoindex.connectors import google_driveThis connector requires additional dependencies. Install with:
pip install cocoindex[google_drive]As source
The connector provides two ways to read from Google Drive:
GoogleDriveSource— high-level source class with async iterationlist_files()— lower-level function returning a sync iterator
Both authenticate with one of:
- a service account with access to the target Drive folders (
service_account_credential_path), the fit for a shared or automated setup; - a personal Google account signed in once through OAuth (
user_account, experimental), the fit for your own Drive: see Signing in with a personal account.
Setting up a service account
- Create a service account in the Google Cloud Console
- Download the JSON credential file
- Share the target Drive folders with the service account’s email address
gws is an optional, unofficial Google Workspace CLI. It is actively developed and subject to change, but can be useful for exploring or validating Drive API access before configuring CocoIndex’s service-account flow. For example:
gws auth setup
gws auth login
gws drive files listIn headless or agent workflows, gws can also read credentials from GOOGLE_WORKSPACE_CLI_CREDENTIALS_FILE. CocoIndex still expects the service account JSON path in service_account_credential_path; use the gws credentials setting for gws commands themselves.
GoogleDriveSource
The primary source class for iterating over Google Drive files.
class GoogleDriveSource(
*,
root_folder_ids: Sequence[str],
service_account_credential_path: str | None = None,
user_account: UserAccount | None = None,
mime_types: Sequence[str] | None = None,
)Parameters:
root_folder_ids— List of Google Drive folder IDs to scan. Subfolders are traversed recursively.service_account_credential_path— Path to the service account JSON credential file.user_account— AUserAccountsigned in through OAuth (experimental). Exactly one ofservice_account_credential_pathanduser_accountis given.mime_types— Optional list of MIME types to include. IfNone, all file types are included.
Iterating files
GoogleDriveSource provides async iteration via files(), yielding DriveFile objects (implementing the FileLike base class):
source = google_drive.GoogleDriveSource(
service_account_credential_path="./credentials.json",
root_folder_ids=["1abc...xyz"],
)
async for file in source.files():
text = await file.read_text()
...Keyed iteration with items()
items() yields (str, DriveFile) pairs keyed by the file’s Google Drive ID. IDs remain stable across renames and avoid collisions when files share a name, including within the same folder. This is useful with mount_each():
async for key, file in source.items():
content = await file.read()Filtering by MIME type
Use mime_types to restrict which files are returned:
source = google_drive.GoogleDriveSource(
service_account_credential_path="./credentials.json",
root_folder_ids=["1abc...xyz"],
mime_types=["application/pdf", "text/plain"],
)Google Workspace files (Docs, Sheets, Slides) are automatically exported:
| Google Workspace type | Exported as |
|---|---|
| Google Docs | Plain text |
| Google Sheets | CSV |
| Google Slides | Plain text |
list_files
A lower-level sync iterator for listing files:
def list_files(spec: GoogleDriveSourceSpec) -> Iterator[DriveFile]Parameters:
spec— AGoogleDriveSourceSpecwith the same fields asGoogleDriveSourceconstructor parameters.
Returns: A sync iterator of DriveFile objects.
DriveFile
DriveFile implements FileLike with Google Drive-specific behavior:
info— TheDriveFileInfothe listing returned: file ID, name, MIME type, size, modified time and MD5 checksum (binary files only).file_path— ADriveFilePathcontaining the path relative to the configured root folder;resolve()returns the Google Drive file ID. If roots overlap or a file is reachable more than once, it is emitted once using the first path encountered in breadth-first traversal. Each folder’s children are visited in order of name, then ID, so the same path is kept on every run.read()/read_text()— Downloads file content via the Google Drive API. Partial reads (sizeparameter) are not supported.
- Every Drive API request, listing and download alike, is retried with backoff (up to five more attempts) when Google answers with a server error, HTTP 429, or 403 with a rate-limit reason, or when the connection fails.
- Change detection uses the Drive MD5 checksum of binary files, so an unchanged file is not downloaded again. Google Docs, Sheets and Slides have no checksum; their exported content is hashed instead.
Signing in with a personal account
UserAccount and the cocoindex auth commands are experimental. Experimental APIs are outside CocoIndex’s compatibility promise: a later release, including a minor one, may change their API or semantics, or remove them.
A service account only sees folders shared with it. To read your own Drive, sign in with your Google account instead. The sign-in is a one-time interactive step, run from the shell, outside any CocoIndex run; it uses the OAuth flow Google recommends for command-line applications (an authorization code with PKCE, redirected to a listener on this machine’s loopback interface), from a Desktop app OAuth client. CocoIndex asks for read-only access to Drive (drive.readonly) and nothing else. CocoIndex’s use and transfer of information received from Google APIs adheres to the Google API Services User Data Policy, including the Limited Use requirements; see how CocoIndex handles Google user data.
CocoIndex’s own OAuth client is not in a release yet: Google has to verify it first. Until a release includes it, sign in with an OAuth client you create in your own Google Cloud project, as below. A release that includes it needs nothing but your Google account: cocoindex auth sign-in google-drive without a client file.
Setting up the OAuth client
Once per Google Cloud project:
- In the Google Cloud Console, create a project (or pick one) and enable the Google Drive API under APIs & Services > Library.
- Under APIs & Services > OAuth consent screen (called Google Auth Platform in newer consoles), configure the consent screen: external user type, any app name, your email as the contact. Leave the publishing status at Testing and add your own Google account under Test users.
- Under APIs & Services > Credentials, create an OAuth client ID of type Desktop app and download its JSON file.
What to expect from a client you own, as Google documents it:
drive.readonlyis a restricted scope, so Google would require app verification (and a security assessment) before the public could use the client. Neither applies to a client in Testing status used by its listed test users, which is the setup for reading your own Drive.- In Testing status, Google expires the consent seven days after it was given: a run then fails with
SignInRequiredErrorand you sign in again. Publishing the client to In production without verification removes the seven-day limit; the consent screen then shows an “unverified app” warning you pass through Advanced, and the client is limited to 100 users over its lifetime. - The downloaded JSON contains a client secret. For a Desktop app Google treats it as not confidential, but keep the file out of git all the same; CocoIndex copies what it needs into the token file and never writes either into the state database, a memo key or a log.
Signing in
cocoindex auth sign-in google-drive ~/Downloads/client_secret_XXXX.json
Without the file argument, the command uses CocoIndex’s own OAuth client, and a release that doesn’t include one says so.
The command opens the consent page in your browser. Approve the request, including the Google Drive permission; the browser lands on a page that says the sign-in completed, and the terminal prints the signed-in address.
On a machine with no browser (over SSH, or with no display), the command prints the link instead. Open it in a browser on another machine and sign in; the browser then lands on http://127.0.0.1:<port>/?code=...&state=... and fails to load, since that address is the other machine. Copy the whole address from the address bar and paste it into the terminal. (If you forward the port with ssh -L <port>:127.0.0.1:<port> <host> in a second session, the page loads instead and nothing is left to paste.)
The tokens are stored at ~/.config/cocoindex/google_drive_token.json on Linux and macOS (under $XDG_CONFIG_HOME when set) and under %APPDATA%\cocoindex on Windows; --token-path picks another location.
The token file holds a long-lived refresh token with read access to your whole Drive, in plain text, next to the OAuth client’s secret. On macOS and Linux, CocoIndex creates it with mode 0600 (readable by your user only), and the connector refuses a token file that other users can access. On Windows there is no such check: the file is as private as its folder, which for the default location is your user profile. Either way, any process that runs as your user can read it. Don’t commit it to git, sync it to cloud storage or copy it into a container image. If it may have leaked, revoke the sign-in: run cocoindex auth sign-out google-drive, or remove the app’s access at myaccount.google.com/permissions.
cocoindex auth sign-out google-drive # revokes the sign-in at Google and deletes the token file
The same two steps are available in Python as UserAccount().sign_in(client_secrets_path) (with no argument for CocoIndex’s own client) and UserAccount().sign_out(); see Signing in from your own program.
Signing in from your own program
A program can sign in by itself instead of asking you to run the command first: check is_signed_in(), and call sign_in() when it is false, before the app runs.
sign_inwaits for a person, up to five minutes, to finish the consent in the browser. So call it before the run starts, never from inside the run.- On a host with no browser, it prints the link and reads the address the browser lands on, pasted back into the terminal, as the command does.
- The command and the library use the same token file, at the same default location, so a sign-in with one serves the other.
is_signed_in()reads only the token file. A stored sign-in that Google has since refused (the consent expired or was revoked) still counts; the run then fails withSignInRequiredError, and you sign in again.
import cocoindex as coco
from cocoindex.connectors import google_drive
account = google_drive.UserAccount()
@coco.fn
async def app_main(folder_ids: list[str]) -> None:
source = google_drive.GoogleDriveSource(
root_folder_ids=folder_ids,
user_account=account,
)
with coco.component_subpath("file"):
async for key, file in source.items():
await coco.mount(coco.component_subpath(key), process_file, file)
app = coco.App("GoogleDriveIngestion", app_main, folder_ids=["1abc...xyz"])
if __name__ == "__main__":
if not account.is_signed_in():
# A client file of your own; no argument for CocoIndex's own client.
email = account.sign_in("client_secret.json")
print(f"Signed in as {email}.")
app.update_blocking(report_to_stdout=True)UserAccount
class UserAccount(token_path: str | os.PathLike[str] | None = None)
UserAccount.token_path -> Path
UserAccount.sign_in(client_secrets_path: str | os.PathLike[str] | None = None) -> str
UserAccount.sign_out() -> bool
UserAccount.email -> str
UserAccount.is_signed_in() -> boolUserAccount() uses the default token path; token_path picks another location (a leading ~ is expanded), and the token_path property returns the path in use. sign_in returns the signed-in address; client_secrets_path is the JSON of a Desktop app client of your own, and without it the sign-in uses CocoIndex’s own client and raises SignInError when the release has none. sign_out revokes the stored sign-in at Google, deletes the token file even when Google can’t be reached, and returns whether the file existed. email raises SignInRequiredError when no sign-in is stored. is_signed_in() raises SignInError when the file exists but other users can access it or it can’t be read.
The handle a run passes to GoogleDriveSource. It reads the token file at token_path (default: the path sign-in writes to) when the source is first used:
- the access token is refreshed with the stored refresh token as it expires, and the refreshed token is written back to the file;
emailis the signed-in account’s address, and the memo key of aUserAccountis that address: a refreshed token does not invalidate memoized work, a different account does;- when no sign-in is stored, or Google refuses the stored one (the consent expired or was revoked, or the OAuth client was deleted, disabled or given a new secret), the run raises
SignInRequiredError(aSignInError), whose message says which and to sign in again. The message never contains a token.
import cocoindex as coco
from cocoindex.connectors import google_drive
@coco.fn
async def app_main(folder_ids: list[str]) -> None:
source = google_drive.GoogleDriveSource(
root_folder_ids=folder_ids,
user_account=google_drive.UserAccount(),
)
with coco.component_subpath("file"):
async for key, file in source.items():
await coco.mount(coco.component_subpath(key), process_file, file)Example
import cocoindex as coco
from cocoindex.connectors import google_drive
from cocoindex.resources.file import FileLike
@coco.fn(memo=True)
async def process_file(file: FileLike) -> None:
text = await file.read_text()
# ... process the file content ...
@coco.fn
async def app_main(credential_path: str, folder_ids: list[str]) -> None:
source = google_drive.GoogleDriveSource(
service_account_credential_path=credential_path,
root_folder_ids=folder_ids,
)
with coco.component_subpath("file"):
async for key, file in source.items():
await coco.mount(
coco.component_subpath(key),
process_file,
file,
)
app = coco.App(
"GoogleDriveIngestion",
app_main,
credential_path="./credentials.json",
folder_ids=["1abc...xyz"],
)