Facebook-lead-ads Python API Docs | dltHub
Build a Facebook-lead-ads-to-database pipeline in Python using dlt with AI Workbench support for Claude Code, Cursor, and Codex.
Last updated:
Facebook Lead Ads is a service that lets advertisers create lead generation forms on Facebook and Instagram and retrieve leads via the Graph API or Webhooks. The REST API base URL is https://graph.facebook.com and All requests require an access token (Page or User); Page access tokens are recommended for lead retrieval..
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 Facebook-lead-ads data in under 10 minutes.
What data can I load from Facebook-lead-ads?
Here are some of the endpoints you can load from Facebook-lead-ads:
| Resource | Endpoint | Method | Data selector | Description |
|---|---|---|---|---|
| leadgen_forms | {page_id}/leadgen_forms | GET | data | List lead forms for a Page (fields parameter supported) |
| leads | {form_id}/leads | GET | data | List leads for a form (supports fields, filtering, paging) |
| lead | {lead_id} | GET | Retrieve a single lead by leadgen_id (returns lead object with field_data) | |
| subscribed_apps | {page_id}/subscribed_apps | GET | data | List Webhook subscriptions for a Page (installation status) |
| test_leads | {form_id}/test_leads | GET | data | Read test leads for a Lead Form (used during testing) |
| export_csv | /ads/lead_gen/export_csv/ | GET | Export leads CSV by form with from_date/to_date query parameters |
How do I authenticate with the Facebook-lead-ads API?
The Graph API uses OAuth access tokens. Include a Page or User access token either as the access_token query parameter or in the Authorization: Bearer header. Use Page access tokens and the leads_retrieval permission for full lead data and ads_management/pages permissions for ad-level fields.
1. Get your credentials
- Create a Meta App in App Dashboard. 2) Add Facebook Login and Webhooks as needed. 3) Request necessary permissions (leads_retrieval, pages_read_engagement, pages_show_list, pages_manage_ads, ads_management) and submit for App Review. 4) Have a Page admin log in to your app and request a Page access token (exchange short-lived token for long-lived and generate a Page token if needed). 5) Install the app on the Page and, if using webhooks, subscribe the Page to the leadgen field.
2. Add them to .dlt/secrets.toml
[sources.facebook_lead_ads_source] access_token = "your_page_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 Facebook-lead-ads 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 facebook_lead_ads_pipeline.py
If everything is configured correctly, you'll see output like this:
Pipeline facebook_lead_ads_pipeline load step completed in 0.26 seconds 1 load package(s) were loaded to destination duckdb and into dataset facebook_lead_ads_data The duckdb destination used duckdb:/facebook_lead_ads.duckdb location to store data Load package 1749667187.541553 is LOADED and contains no failed jobs
Inspect your pipeline and data:
dlt pipeline facebook_lead_ads_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 leadgen_forms and leads from the Facebook-lead-ads 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 facebook_lead_ads_source(access_token=dlt.secrets.value): config: RESTAPIConfig = { "client": { "base_url": "https://graph.facebook.com", "auth": { "type": "bearer", "token": access_token, }, }, "resources": [ {"name": "leadgen_forms", "endpoint": {"path": "{page_id}/leadgen_forms", "data_selector": "data"}}, {"name": "leads", "endpoint": {"path": "{form_id}/leads", "data_selector": "data"}} ], } yield from rest_api_resources(config) def get_data() -> None: pipeline = dlt.pipeline( pipeline_name="facebook_lead_ads_pipeline", destination="duckdb", dataset_name="facebook_lead_ads_data", ) load_info = pipeline.run(facebook_lead_ads_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("facebook_lead_ads_pipeline").dataset() sessions_df = data.leads.df() print(sessions_df.head())
SQL (DuckDB example):
SELECT * FROM facebook_lead_ads_data.leads LIMIT 10;
In a marimo or Jupyter notebook:
import dlt data = dlt.pipeline("facebook_lead_ads_pipeline").dataset() data.leads.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 Facebook-lead-ads data to?
dlt supports loading into any of these destinations — only the destination parameter changes:
| Destination | Example 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 your access token is missing, invalid, expired or lacks required scopes (for example leads_retrieval, pages_read_engagement, ads_management), the Graph API returns OAuth errors. Use a Page access token requested by a Page admin who can advertise on the Page for lead retrieval; exchange short-lived tokens for long-lived tokens and generate a long-lived Page token.
Rate limits
Lead retrieval rate limit: 200 * 24 * (number of leads created in past 90 days) calls per 24-hour period for a Page. Exceeding this returns rate-limit errors; batch or pace requests and prefer Webhooks for real-time ingestion.
Pagination and cursors
List responses (lead lists and form lists) use the top-level "data" array and a "paging" object with cursors (before/after). Use the paging.cursors.after value to page forward or the provided next URL when present.
Webhooks and real-time reliability
Subscribe the Page to the leadgen field on the Webhooks product and install the app on the Page. Webhook notifications include an entry array with changes and leadgen_id values; use leadgen_id to call GET /<LEAD_ID>?fields=... to fetch lead details. Monitor RTU delivery status in the dashboard and handle retry/backoff for failed deliveries.
Common API errors:
- OAuthException: Invalid or expired token or missing permissions.
- (#4) Application request limit reached: rate limiting.
- (#1) Unknown error: transient Graph API errors; retry with backoff.
- 10, 2: Permission or server errors related to ads/lead access.
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 Facebook-lead-ads?
Request dlt skills, commands, AGENT.md files, and AI-native context.