Pulling Data from Connect: A Guide for Data Engineers
This page explains how Connect partners can export data from Connect into their own data warehouse or reporting system. It is intended for users with technical expertise and familiarity with Application Programming Interfaces (APIs).
- 1 1. Context
- 2 2. Before you start checklist
- 3 3. Authentication
- 4 4. Making your first call
- 5 5. Common data-pull workflows
- 5.1 5.1 Inventory of organizations, programs, and opportunities
- 5.2 5.2 Opportunity detail
- 5.3 5.3 FLW roster and cumulative status (user_data)
- 5.4 5.4 Individual visits (user_visits)
- 5.5 5.5 Completed deliveries (completed_works)
- 5.6 5.6 Learn module completion (completed_module)
- 5.7 5.7 Incremental vs full sync
- 6 6. Read-only API reference
- 7 7. Permission model
- 8 8. Operational guidance
- 9 9. Security checklist
- 10 10. Versioning & change management
- 11 11. Appendix
1. Context
This guide is for a data engineer or technical team that wants to pull data out of Connect and into their own analytics environment - Apache Superset, a Postgres warehouse, BigQuery, Snowflake, a flat-file CSV pipeline, or any other tool of choice.
It covers read-only access only.
After reading this guide your team will be able to:
Authenticate as a Network Manager using OAuth and refresh tokens.
Pull your program portfolio, opportunities, FLW status, deliveries, and learn-module completions on a schedule.
Load them into a data warehouse or directly into Superset for dashboards.
Run incremental refreshes without re-downloading everything every night.
Product and domain concepts (programs, opportunities, LLOs, FLWs, payment units, etc.) live on the Connect public wiki. This guide focuses on the integration mechanics.
2. Before you start checklist
3. Authentication
Connect uses OAuth 2.0. All API calls require a Bearer access token in the Authorization header. Tokens are short-lived; use the refresh-token flow to keep a long-running sync alive.
3.1 Requesting an OAuth client
Email Dimagi Connect support with:
Your organization name and the Network Manager account that will own the client.
A short description of your integration’s purpose (for instance, “nightly pull into Superset”).
Expected request volume - rough orders of magnitude are fine.
You will receive back a client_id and client_secret. Treat the client_secret like a password.
3.2 Password grant flow
Connect supports the OAuth 2.0 Resource Owner Password Credentials grant (oauth.net/2/grant-types/password). It is the simplest flow when the integration is owned and run by the same Network Manager whose data is being pulled - there is no browser redirect and no callback endpoint.
Send the Network Manager’s Connect username and password directly to the token endpoint:
POST https://connect.dimagi.com/o/token/
Content-Type: application/x-www-form-urlencoded
grant_type=password
&username=YOUR_CONNECT_USERNAME
&password=YOUR_CONNECT_PASSWORD
&client_id=YOUR_CLIENT_ID
&client_secret=YOUR_CLIENT_SECRET
&scope=exportResponse shape:
{
"access_token": "...",
"refresh_token": "...",
"expires_in": 3600,
"token_type": "Bearer",
"scope": "export"
}For a background data sync, run this call once from a secure machine (your laptop, a bastion, or your CI bootstrap step), capture the refresh_token, and store it in your secrets manager. From then on the script silently refreshes (Section 3.3) and the username and password are not needed again unless the refresh token is revoked or expires.
When to use this flow. It is intended for first-party integrations where the human running the integration is the Network Manager. If you are building a third-party application that asks other Network Managers to authorize access to their accounts, use the Authorization Code flow instead.
Security notes.
The Connect username and password give full account access. Treat them like any production secret: store in a vault, never commit to source control, never log.
Do not persist the password after the first /o/token/ call. Keep only the refresh_token, which can be revoked independently if compromised.
If your account uses SSO or MFA on the Connect UI, the password grant may not work for it - contact Dimagi support to confirm before adopting this flow.
3.3 Refresh token loop
Access tokens expire (commonly after 1 hour). Refresh before each sync run:
POST https://connect.dimagi.com/o/token/
Content-Type: application/x-www-form-urlencoded
grant_type=refresh_token
&refresh_token=YOUR_REFRESH_TOKEN
&client_id=YOUR_CLIENT_ID
&client_secret=YOUR_CLIENT_SECRETThe response may include a rotated refresh_token. Always persist whichever refresh token was returned most recently - otherwise the next run will fail with invalid_grant.
3.4 Token storage
Store client_secret, access_token, and refresh_token in a secrets manager (AWS Secrets Manager, HashiCorp Vault, Doppler, GCP Secret Manager, or an equivalent).
Never log full token values. If you must log for debugging, mask all but the last 4 characters.
Rotate client_secret at least annually, and immediately on any suspected leak.
3.5 “I got a 401” checklist
Authorization header is literally Bearer <token> with one space and no quotes.
access_token has not expired (refresh 60 seconds early).
Base URL is http://connect.dimagi.com (not commcarehq.org).
refresh_token is the most recent one returned, not an older copy.
Connect user behind the token is still a Network Manager on the programs you’re hitting.
4. Making your first call
The simplest sanity check is GET /export/opp_org_program_list/. This single call returns everything your token can see - the organizations, programs, and opportunities the Network Manager behind the token is associated with - and is the recommended entry point for any new integration. Hit it once and you know what scope you have to work with before issuing any other call.
Python (httpx)
import httpx
ACCESS_TOKEN = "..."
BASE_URL = "https://connect.dimagi.com"
resp = httpx.get(
f"{BASE_URL}/export/opp_org_program_list/",
headers={"Authorization": f"Bearer {ACCESS_TOKEN}"},
timeout=30.0,
)
resp.raise_for_status()
data = resp.json()
print("Organizations:", len(data.get("organizations", [])))
print("Programs: ", len(data.get("programs", [])))
print("Opportunities:", len(data.get("opportunities", [])))curl
curl -H "Authorization: Bearer $ACCESS_TOKEN" \
https://connect.dimagi.com/export/opp_org_program_list/What you get back. A JSON object with three top-level lists - organizations, programs, and opportunities - covering everything the token user has membership in. Each opportunity carries the program_id and organization_id it belongs to, so you can stitch the three together client-side without any further calls.
If any of those lists is empty, confirm the Network Manager behind the token actually has access to that resource type in the Connect UI. The API will not return resources the user cannot see.
5. Common data-pull workflows
All endpoints below live under the /export/ namespace and are documented in /api/docs/#/export. Two conventions apply to every call in this section:
Always send the v2 Accept header - Accept: application/json; version=2.0. Without it the server may fall back to an older payload shape and your sync will silently break when v1 is retired.
All list endpoints are keyset-paginated. Each response carries a next URL; walk it until null. The server preserves your page_size on the next URL - set it once on the first call. Server default is 1000, maximum is 5000.
A minimal reusable client wraps both:
import httpx
def make_client(access_token: str) -> httpx.Client:
return httpx.Client(
base_url="https://connect.dimagi.com",
headers={
"Authorization": f"Bearer {access_token}",
"Accept": "application/json; version=2.0",
},
timeout=60.0,
follow_redirects=True,
)
def paginated(client, path, params=None):
params = dict(params or {})
params.setdefault("page_size", 2500)
url = path
while url:
resp = client.get(url, params=params if url == path else None)
resp.raise_for_status()
body = resp.json()
yield from body["results"]
url = body.get("next")Each workflow below lists the endpoint, what it returns, the recommended schedule, and any known gotchas.
5.1 Inventory of organizations, programs, and opportunities
Covered in section 4 - GET /export/opp_org_program_list/ returns everything your token can see in a single call. The opportunity_id values it surfaces are the input to every other endpoint in this section.
Recommended cadence: daily.
5.2 Opportunity detail
GET /export/opportunity/{opportunity_id}/Returns the full opportunity record - name, status, dates, configuration, totals. Use this when the lean payload from opp_org_program_list doesn’t have the field you need.
Recommended cadence: daily, or on-demand alongside other pulls.
5.3 FLW roster and cumulative status (user_data)
GET /export/opportunity/{opportunity_id}/user_data/Returns one row per frontline worker enrolled in the opportunity, with their cumulative delivery/learn status, payments, and flags. This is the standard “who is on this opportunity and how are they doing” feed.
for opp in opportunities:
for flw in paginated(client, f"/export/opportunity/{opp['id']}/user_data/"):
warehouse.upsert(
table="flw_status",
key=("opportunity_id", "username"),
row={"opportunity_id": opp["id"], **flw},
)Gotcha: this endpoint does not include an internal user_id; the stable identifier per FLW is username scoped to the opportunity. Use (opportunity_id, username) as your warehouse key.
Recommended cadence: hourly during active programs, daily otherwise.
5.4 Individual visits (user_visits)
GET /export/opportunity/{opportunity_id}/user_visits/Returns one row per FLW visit (form submission) recorded for the opportunity - timestamps, location, form data, review status. This is the granular source of truth for delivery analytics.
Gotcha: visit volumes can be large. Use a healthy page_size (2500–5000) and consider incremental pulls (Section 5.7) once you’ve done the first full backfill.
Recommended cadence: hourly during active programs.
5.5 Completed deliveries (completed_works)
GET /export/opportunity/{opportunity_id}/completed_works/Returns the rolled-up “completed work” entries the opportunity uses to drive payment. Each row represents a unit of work an FLW finished against a payment unit. Lower volume than user_visits and the right source if you want payment-eligible counts rather than raw form submissions.
Recommended cadence: hourly during active programs.
5.6 Learn module completion (completed_module)
GET /export/opportunity/{opportunity_id}/completed_module/Returns one row per FLW per learn module completion, with timestamps and assessment scores. Use this to track training progress separately from delivery work.
Recommended cadence: daily.
5.7 Incremental vs full sync
Most of the high-volume endpoints (user_visits, completed_works) expose a timestamp field you can use as a watermark:
Track the maximum visit/completion timestamp you have ingested per opportunity in your warehouse.
On each subsequent run, filter the API call with the supported since parameter when offered, and ignore rows older than your watermark when not.
Run a full backfill weekly to catch edits to previously-synced rows.
Confirm exact filter parameter names per endpoint against the Connect OpenAPI schema - they vary, and the schema is the source of truth.
6. Read-only API reference
All endpoints below live under /export/ on https://connect.dimagi.com and are documented in the export section of /api/docs/. Only GET is supported.
Two conventions apply to every call:
Send Accept: application/json; version=2.0 to opt into the v2 payload shape.
List endpoints are keyset-paginated - follow the next URL until null. Set page_size on the first request (default 1000, max 5000); the server preserves it on subsequent next URLs.
6.1 Inventory
Path | Purpose | Notes |
/export/opp_org_program_list/ | Returns the organizations, programs, and opportunities the token user can see. | Single non-paginated response. Use this first - the opportunity_id values it surfaces are input to every endpoint below. |
6.2 Opportunity
Path | Purpose | Notes |
/export/opportunity/{opportunity_id}/ | Full opportunity record - name, status, dates, configuration, totals. | Single object response. |
6.3 Workers and deliveries
Path | Purpose | Notes |
/export/opportunity/{opportunity_id}/user_data/ | One row per frontline worker on the opportunity, with cumulative status, payments, and flags. | Stable key is (opportunity_id, username) - there is no internal user_id on this payload. |
/export/opportunity/{opportunity_id}/user_visits/ | One row per FLW visit (form submission) - timestamps, location, form data, review status. | Highest-volume endpoint. Use a page_size of 2500–5000 and consider incremental pulls. Pass images=true to receive image URLs alongside each visit. |
/export/opportunity/{opportunity_id}/completed_works/ | Rolled-up “completed work” entries that drive payment, one per payment-unit completion per FLW. | Lower volume than user_visits. Use this for payment-eligible counts. |
/export/opportunity/{opportunity_id}/completed_module/ | One row per FLW per learn-module completion, with timestamps and assessment scores. | Use this to track training progress separately from delivery work. |
6.4 Media and app schema
Path | Purpose | Notes |
/export/opportunity/{opportunity_id}/image/ | Image binaries captured during visits. | Streams binary payloads - not paginated JSON. Use only when you specifically need the image files; user_visits?images=true is enough if you just need URLs. |
/export/opportunity/{opportunity_id}/app_structure/ | Form-by-form structure of the CommCare app(s) backing the opportunity (form names, question paths, choice lists). | Use this if you want to interpret raw user_visits form data - it tells you what each field path means. Mostly stable; pull on demand rather than on a schedule. |
The full parameter matrix and exact field shapes live in the Connect OpenAPI schema at /api/docs/#/export - treat that as the source of truth and this table as a quick map. If you spot an export endpoint there that isn’t listed here, it likely exists and works; let your Dimagi POC know so this doc can be updated.
7. Permission model
Rule of thumb: if you can see it in the Connect UI as a Network Manager, you can read it via the API as that same user.
404 Not Found - resource doesn’t exist, or the user behind the token is not in the owning organization. Connect collapses both into 404 to avoid leaking existence.
403 Forbidden - user is in the right organization but lacks the role to read this resource.
401 Unauthorized - token is invalid, expired, or revoked. See Section 3.5.
8. Operational guidance
8.1 Rate limits and backoff
Plan for a sustained ceiling of roughly a few requests per second per OAuth client. Above that you will see 429 Too Many Requests with a Retry-After header. Implement exponential backoff with jitter:
import time, random
def call_with_backoff(fn, max_attempts=5):
for attempt in range(max_attempts):
resp = fn()
if resp.status_code != 429:
return resp
delay = int(resp.headers.get("Retry-After", 2 ** attempt))
time.sleep(delay + random.uniform(0, 1))
raise RuntimeError("rate limit retries exhausted")8.2 Pagination
List endpoints return:
{
"count": 137,
"next": "https://connect.dimagi.com/export/opportunity/42/user_visits/?page_size=2500&cursor=cD0yMDI1...",
"previous": null,
"results": [ ... ]
}Walk next until null. Use the URL Connect gives you - do not hand-build page= URLs.
8.3 Error response shapes
Status | Meaning | Action |
2xx | Success | Process the body. |
400 | Validation error | Try by looking at the error message. If the issue persists, reach out to Dimagi dev. |
401 | Token invalid/expired | Refresh and retry once. |
403 | User lacks role | Double-check the opportunity id to make sure you are requesting the right info, and make sure your user is correct and has access to the organisation you are looking at. |
404 | Not found / no access | Verify scoping; do not retry. |
429 | Rate limited | Backoff (Section 8.1). |
5xx | Server error | Retry with backoff; alert if persistent. |
8.4 Idempotency in your warehouse
Use the Connect record id as the primary key in your warehouse table. INSERT … ON CONFLICT UPDATE (or your warehouse’s MERGE equivalent) makes reruns safe.
Stamp every row with synced_at = now() so you can spot stale rows.
Don’t delete rows just because they disappeared from the API - soft-delete with a deleted_at column to preserve history.
8.5 Logging and PII
Do not log full access_token or refresh_token values. Mask all but the last 4 characters.
FLW phone numbers and personal identifiers are PII. Apply your organization’s PII handling standards to anything you log or persist.
Log the X-Request-Id response header when present - Dimagi support uses it to trace issues.
8.6 Putting it in Superset
Two common patterns:
Warehouse + Superset (recommended). Land data in Postgres / MySQL / BigQuery via your sync script, then point Superset at the warehouse as a database. You get joins, dbt-friendly models, and proper SQL exploration.
CSV + Superset upload. Sync to CSVs, upload via Superset’s CSV-to-database feature. Fine for ad-hoc exploration, brittle for production dashboards.
A minimal warehouse schema:
organizations (id PK, name, ..., synced_at) |
From there, every Superset dashboard is just SQL on the warehouse - no API calls in the hot path.
9. Security checklist
All API calls over TLS 1.2+. The API will refuse plain HTTP.
Tokens go in the Authorization header, never in query strings.
Rotate client_secret at least annually, and immediately on any suspected leak.
Scope minimization - request only the scope your sync needs.
Use a dedicated OAuth client per environment (production, staging, dev).
If a token leaks, contact Dimagi support immediately to revoke and rotate.
10. Versioning & change management
Documented endpoints are stable; breaking changes are announced in advance via the partner mailing list.
Additive changes (new optional fields, new endpoints) may ship without notice - code defensively against unexpected fields.
Deprecation policy: deprecated endpoints remain available for at least 90 days after announcement before removal.
Subscribe to the partner mailing list (ask your Dimagi POC) for advance notice.
11. Appendix
11.1 Worked example: nightly sync to Postgres for Superset
A minimal Python script your team can fork. Pulls the opportunity inventory, then for each opportunity the FLW roster, completed works, and module completions, and lands them in a Postgres warehouse via upsert. Run nightly (or hourly) via cron, Airflow, or any orchestrator. Superset then points at the same Postgres for dashboards - no API calls in the hot path.
#!/usr/bin/env python3
"""Nightly Connect -> Postgres sync for Superset."""
import os, httpx, psycopg2
from psycopg2.extras import Json
BASE = "https://connect.dimagi.com"
TOKEN = os.environ["CONNECT_ACCESS_TOKEN"] # refresh upstream of this script
PG_DSN = os.environ["WAREHOUSE_DSN"]
client = httpx.Client(
base_url=BASE,
headers={
"Authorization": f"Bearer {TOKEN}",
"Accept": "application/json; version=2.0",
},
timeout=60.0,
follow_redirects=True,
)
def paginated(path, params=None):
"""Walk next URLs until null. page_size is preserved by the server."""
params = dict(params or {})
params.setdefault("page_size", 2500)
url = path
while url:
resp = client.get(url, params=params if url == path else None)
resp.raise_for_status()
body = resp.json()
yield from body["results"]
url = body.get("next")
UPSERT_ORG = """
INSERT INTO organizations (id, name, raw, synced_at)
VALUES (%s, %s, %s, now())
ON CONFLICT (id) DO UPDATE
SET name = EXCLUDED.name, raw = EXCLUDED.raw, synced_at = now();
"""
UPSERT_PROGRAM = """
INSERT INTO programs (id, name, organization_id, raw, synced_at)
VALUES (%s, %s, %s, %s, now())
ON CONFLICT (id) DO UPDATE
SET name = EXCLUDED.name, organization_id = EXCLUDED.organization_id,
raw = EXCLUDED.raw, synced_at = now();
"""
UPSERT_OPP = """
INSERT INTO opportunities (id, program_id, name, status, raw, synced_at)
VALUES (%s, %s, %s, %s, %s, now())
ON CONFLICT (id) DO UPDATE
SET program_id = EXCLUDED.program_id, name = EXCLUDED.name,
status = EXCLUDED.status, raw = EXCLUDED.raw, synced_at = now();
"""
UPSERT_FLW = """
INSERT INTO flw_status (opportunity_id, username, raw, synced_at)
VALUES (%s, %s, %s, now())
ON CONFLICT (opportunity_id, username) DO UPDATE
SET raw = EXCLUDED.raw, synced_at = now();
"""
UPSERT_COMPLETED_WORK = """
INSERT INTO completed_works (id, opportunity_id, raw, synced_at)
VALUES (%s, %s, %s, now())
ON CONFLICT (id) DO UPDATE
SET opportunity_id = EXCLUDED.opportunity_id,
raw = EXCLUDED.raw, synced_at = now();
"""
UPSERT_COMPLETED_MODULE = """
INSERT INTO completed_modules (id, opportunity_id, raw, synced_at)
VALUES (%s, %s, %s, now())
ON CONFLICT (id) DO UPDATE
SET opportunity_id = EXCLUDED.opportunity_id,
raw = EXCLUDED.raw, synced_at = now();
"""
# Step 1: inventory - single call, returns orgs + programs + opps the token can see.
inventory = client.get("/export/opp_org_program_list/")
inventory.raise_for_status()
inv = inventory.json()
with psycopg2.connect(PG_DSN) as conn, conn.cursor() as cur:
for org in inv.get("organizations", []):
cur.execute(UPSERT_ORG, (org["id"], org.get("name"), Json(org)))
for prog in inv.get("programs", []):
cur.execute(UPSERT_PROGRAM, (
prog["id"], prog.get("name"), prog.get("organization_id"), Json(prog),
))
for opp in inv.get("opportunities", []):
cur.execute(UPSERT_OPP, (
opp["id"], opp.get("program_id"), opp.get("name"),
opp.get("status"), Json(opp),
))
# Step 2: per-opportunity pulls.
for opp in inv.get("opportunities", []):
opp_id = opp["id"]
for flw in paginated(f"/export/opportunity/{opp_id}/user_data/"):
cur.execute(UPSERT_FLW, (opp_id, flw["username"], Json(flw)))
for work in paginated(f"/export/opportunity/{opp_id}/completed_works/"):
cur.execute(UPSERT_COMPLETED_WORK, (work["id"], opp_id, Json(work)))
for mod in paginated(f"/export/opportunity/{opp_id}/completed_module/"):
cur.execute(UPSERT_COMPLETED_MODULE, (mod["id"], opp_id, Json(mod)))
conn.commit()
print("Sync complete.")What you get. Five tables - organizations, programs, opportunities, flw_status, completed_works, completed_modules - each with a typed primary-key column, a few projected hot columns, and a raw JSONB column carrying the full record. New fields Connect adds upstream show up in raw immediately; promote them to typed columns later if a dashboard needs to filter or sort on them.
Adding user_visits. If you need visit-level analytics, add a user_visits table and a fourth per-opportunity loop calling /export/opportunity/{opp_id}/user_visits/. It is the highest-volume endpoint - switch to incremental syncs (Section 5.7) once the first backfill is done.
In Superset. Add the same Postgres as a database and build datasets/charts directly off these tables. Keep the raw JSONB column on every table so you can surface new fields without re-syncing.
11.2 FAQ
Q: Are webhooks supported?
Not today. Poll on the cadences suggested in Section 5. Ask your Dimagi POC for the current webhook roadmap.
Q: How often should I refresh?
Operational data (user_data, user_visits, completed_works) - hourly during active periods, daily otherwise.
Q: What’s the SLA?
The API tracks production Connect’s availability (target 99.5% monthly uptime).