Gmail Python API Docs | dltHub

Build a Gmail-to-database pipeline in Python using dlt with AI Workbench support for Claude Code, Cursor, and Codex.

Last updated:

Gmail REST API v1 is a service that allows programmatic access to Gmail data, including messages, threads, labels, and drafts. The REST API base URL is https://www.googleapis.com/gmail/v1/ and All requests require an OAuth 2.0 access token for authentication, sent as a Bearer token in the Authorization header..

dlt is an open-source Python library that handles authentication, pagination, and schema evolution automatically. dlthub provides AI context files that enable code assistants to generate production-ready pipelines. Install with uv pip install "dlt[workspace]" and start loading Gmail data in under 10 minutes.


What data can I load from Gmail?

Here are some of the endpoints you can load from Gmail:

ResourceEndpointMethodData selectorDescription
messagesusers.messages.listGETmessagesLists the messages in the user's mailbox.
threadsusers.threads.listGETthreadsLists the threads in the user's mailbox.
labelsusers.labels.listGETlabelsLists the labels in the user's mailbox.
draftsusers.drafts.listGETdraftsLists the drafts in the user's mailbox.
historyusers.history.listGEThistoryLists the history of changes in the user's mailbox.
messages_getusers.messages.getGETGets a specific message by ID.
threads_getusers.threads.getGETGets a specific thread by ID.

How do I authenticate with the Gmail API?

The Gmail API uses OAuth 2.0 for authentication. An access token, obtained through the OAuth flow, must be included in the Authorization header of all requests as a Bearer token (e.g., Authorization: Bearer <token>).

1. Get your credentials

To obtain API credentials, navigate to the Google Cloud Console. From there, you can obtain OAuth client credentials. These credentials are then used to request an access token from the Authorization Server.

2. Add them to .dlt/secrets.toml

[sources.gmail_service_source] client_id = "your_client_id_here" client_secret = "your_client_secret_here" token = "your_access_token_here"

dlt reads this automatically at runtime — never hardcode tokens in your pipeline script. For production environments, see setting up credentials with dlt for environment variable and vault-based options.


How do I set up and run the pipeline?

Set up a virtual environment and install dlt:

uv venv && source .venv/bin/activate uv pip install "dlt[workspace]"

1. Install the dlt AI Workbench:

dlt ai init --agent <your-agent> # <agent>: claude | cursor | codex

This installs project rules, a secrets management skill, appropriate ignore files, and configures the dlt MCP server for your agent. Learn more →

2. Install the rest-api-pipeline toolkit:

dlt ai toolkit rest-api-pipeline install

This loads the skills and context about dlt the agent uses to build the pipeline iteratively, efficiently, and safely. The agent uses MCP tools to inspect credentials — it never needs to read your secrets.toml directly. Learn more →

3. Start LLM-assisted coding:

Use /find-source to load data from the Gmail API into DuckDB.

The rest-api-pipeline toolkit takes over from here — it reads relevant API documentation, presents you with options for which endpoints to load, and follows a structured workflow to scaffold, debug, and validate the pipeline step by step.

4. Run the pipeline:

python gmail_service_pipeline.py

If everything is configured correctly, you'll see output like this:

Pipeline gmail_service_pipeline load step completed in 0.26 seconds 1 load package(s) were loaded to destination duckdb and into dataset gmail_service_data The duckdb destination used duckdb:/gmail_service.duckdb location to store data Load package 1749667187.541553 is LOADED and contains no failed jobs

Inspect your pipeline and data:

dlt pipeline gmail_service_pipeline show

This opens the Pipeline Dashboard where you can verify pipeline state, load metrics, schema (tables, columns, types), and query the loaded data directly.


Python pipeline example

This example loads messages and threads from the Gmail API into DuckDB. It mirrors the endpoint and data selector configuration from the table above:

import dlt from dlt.sources.rest_api import RESTAPIConfig, rest_api_resources @dlt.source def gmail_service_source(client_id, client_secret, token=dlt.secrets.value): config: RESTAPIConfig = { "client": { "base_url": "https://www.googleapis.com/gmail/v1/", "auth": { "type": "oauth2", "token": client_id, client_secret, token, }, }, "resources": [ {"name": "messages", "endpoint": {"path": "users.messages.list", "data_selector": "messages"}}, {"name": "threads", "endpoint": {"path": "users.threads.list", "data_selector": "threads"}} ], } yield from rest_api_resources(config) def get_data() -> None: pipeline = dlt.pipeline( pipeline_name="gmail_service_pipeline", destination="duckdb", dataset_name="gmail_service_data", ) load_info = pipeline.run(gmail_service_source()) print(load_info)

To add more endpoints, append entries from the resource table to the "resources" list using the same name, path, and data_selector pattern.


How do I query the loaded data?

Once the pipeline runs, dlt creates one table per resource. You can query with Python or SQL.

Python (pandas DataFrame):

import dlt data = dlt.pipeline("gmail_service_pipeline").dataset() sessions_df = data.messages.df() print(sessions_df.head())

SQL (DuckDB example):

SELECT * FROM gmail_service_data.messages LIMIT 10;

In a marimo or Jupyter notebook:

import dlt data = dlt.pipeline("gmail_service_pipeline").dataset() data.messages.df().head()

See how to explore your data in marimo Notebooks and how to query your data in Python with dataset.


What destinations can I load Gmail data to?

dlt supports loading into any of these destinations — only the destination parameter changes:

DestinationExample value
DuckDB (local, default)"duckdb"
PostgreSQL"postgres"
BigQuery"bigquery"
Snowflake"snowflake"
Redshift"redshift"
Databricks"databricks"
Filesystem (S3, GCS, Azure)"filesystem"

Change the destination in dlt.pipeline(destination="snowflake") and add credentials in .dlt/secrets.toml. See the full destinations list.


Troubleshooting

Common Errors

  • 401 Unauthorized: This error occurs if the access token is invalid or has expired. Ensure your OAuth 2.0 access token is current and correctly included in the Authorization: Bearer <token> header.
  • 403 Forbidden: This indicates insufficient permissions for the requested operation or that a rate limit has been exceeded. Verify the scopes granted to your application and check for rate limit quotas.
  • 404 Not Found: The requested resource could not be found. This might happen if an ID is incorrect or the resource does not exist.
  • 400 Bad Request: The request was malformed. Check the request body and parameters against the API documentation.
  • 429 Too Many Requests: This error signifies that your application has sent too many requests in a given amount of time, exceeding the API's rate limits.

Pagination

List responses from the Gmail API often include a nextPageToken field. If this field is present, it indicates that there are more results available. To retrieve the next set of results, include the nextPageToken value in a subsequent request. The resultSizeEstimate field provides an estimate of the total number of results.

Ensure that the API key is valid to avoid 401 Unauthorized errors. Also, verify endpoint paths and parameters to avoid 404 Not Found errors.


Next steps

Continue your data engineering journey with the other toolkits of the dltHub AI Workbench:

  • data-exploration — Build custom notebooks, charts, and dashboards for deeper analysis with marimo notebooks.
  • dlthub-runtime — Deploy, schedule, and monitor your pipeline in production.
dlt ai toolkit data-exploration install dlt ai toolkit dlthub-runtime install

Was this page helpful?

Community Hub

Need more dlt context for Gmail?

Request dlt skills, commands, AGENT.md files, and AI-native context.