Mailgun Python API Docs | dltHub

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

Last updated:

Mailgun is a RESTful email delivery platform for sending, receiving, tracking, and validating email at scale. The REST API base URL is https://api.mailgun.net/ (US) ; https://api.eu.mailgun.net/ (EU) and All requests use HTTP Basic auth with your API key as the password..

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 Mailgun data in under 10 minutes.


What data can I load from Mailgun?

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

ResourceEndpointMethodData selectorDescription
domains/v4/domainsGETitemsList domains for the account (v4 domains API)
events/v3/{domain_name}/eventsGETitemsQuery message events (opens, clicks, deliveries, bounces) for a domain
routes/v3/routesGETitemsList inbound email routes configured on the account
lists/v3/listsGETitemsList mailing lists for the account
members/v3/lists/{address}/membersGETitemsList members of a mailing list
bounces/v3/{domain_name}/bouncesGETitemsList bounces (suppression) for a domain
webhooks/v3/domains/{domain}/webhooksGETwebhooksRetrieve domain webhooks (response has webhooks object)
ips/v3/ipsGETitemsList IPs assigned to the account

How do I authenticate with the Mailgun API?

Authentication is HTTP Basic. Use username "api" and your private API key as the password (e.g., curl --user 'api:YOUR_API_KEY'). Include this on every request.

1. Get your credentials

  1. Sign in to the Mailgun Control Panel. 2) Navigate to Account Settings → API Security (or Account → API Keys). 3) Locate the Private API Key and copy it. 4) Keep it secret; use it as the password in HTTP Basic auth with username "api".

2. Add them to .dlt/secrets.toml

[sources.mailgun_source] api_key = "your_mailgun_private_api_key_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 Mailgun 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 mailgun_pipeline.py

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

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

Inspect your pipeline and data:

dlt pipeline mailgun_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 domains and events from the Mailgun 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 mailgun_source(api_key=dlt.secrets.value): config: RESTAPIConfig = { "client": { "base_url": "https://api.mailgun.net/ (US) ; https://api.eu.mailgun.net/ (EU)", "auth": { "type": "http_basic", "api_key": api_key, }, }, "resources": [ {"name": "domains", "endpoint": {"path": "v4/domains", "data_selector": "items"}}, {"name": "events", "endpoint": {"path": "v3/{domain_name}/events", "data_selector": "items"}} ], } yield from rest_api_resources(config) def get_data() -> None: pipeline = dlt.pipeline( pipeline_name="mailgun_pipeline", destination="duckdb", dataset_name="mailgun_data", ) load_info = pipeline.run(mailgun_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("mailgun_pipeline").dataset() sessions_df = data.events.df() print(sessions_df.head())

SQL (DuckDB example):

SELECT * FROM mailgun_data.events LIMIT 10;

In a marimo or Jupyter notebook:

import dlt data = dlt.pipeline("mailgun_pipeline").dataset() data.events.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 Mailgun 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

Authentication failures

If you receive 401 Unauthorized, confirm you are using HTTP Basic auth with username "api" and your Private API Key as the password. Ensure you are using the correct regional base URL (api.mailgun.net for US, api.eu.mailgun.net for EU). Missing or malformed Authorization header and incorrect key are the most common causes.

Rate limiting (429)

Mailgun returns 429 when rate limits are exceeded. Check Retry-After and related rate-limit headers in the response. Implement exponential backoff and respect Retry-After. Contact Mailgun support to request higher limits if required.

Pagination and large result sets

Most listing endpoints return paginated responses with a top-level "items" array and paging links/metadata (e.g., a "paging" object). Use provided next/previous paging links or query params (limit, page, ascending/descending, begin/end timestamps for events) to iterate through results.

Common API errors

  • 400 Bad Request — request invalid; response typically contains a JSON "message" key with details.
  • 401 Unauthorized — invalid/missing API key or incorrect auth format.
  • 403 Forbidden — valid credentials but access to resource denied.
  • 404 Not Found — resource not found; verify endpoint and region.
  • 429 Too Many Requests — rate limit exceeded.
  • 500/502/503 — server errors; retry with exponential backoff.

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 Mailgun?

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