Integrate with a legacy customer system

Build the kind of integration FDEs write in almost every engagement. A fictional customer's policy system exposes an OAuth-protected REST API with cursor pagination, and their claims system drops a nightly CSV file on an SFTP server. You will run realistic mocks of both locally, then build a sync job that authenticates with client credentials, pages through the API incrementally with a watermark, picks up files only when they are complete, validates every record, quarantines bad ones with reasons, upserts idempotently, reconciles counts, and reports health so an operator knows when it breaks.

Intermediate about 6 hours 6 phases · 25 steps 0 / 25 done
What you will have at the end

A repository with mocks/ (OAuth + REST API and an SFTP server in Docker Compose), sync/ (the integration job with tests), a README.md an operator can follow, and a demo log showing a clean run, a re-run with no duplicates, a bad file quarantined, an expired token handled, and a reconciliation alert firing on a deliberate mismatch.

Before you start
  • Python and Docker basics
  • The integration and Python delivery lessons of this track
Tools you will install
  • FastAPI — a mock OAuth token endpoint and paginated REST API ↗
  • atmoz/sftp — a disposable SFTP server for file drops ↗
  • httpx — HTTP client with timeouts ↗
  • paramiko — SFTP client in Python ↗
  • SQLite — the target store, with upserts and a quarantine table ↗
Repository layout at the end
legacy-integration/
├── mocks/
│   ├── api.py              # /oauth/token + /policies with cursors
│   └── compose.yml         # api + sftp
├── sync/
│   ├── config.py           # env-based config
│   ├── auth.py             # client credentials + token cache
│   ├── policies.py         # cursor walk, watermark
│   ├── claims_files.py     # SFTP poller with .done markers
│   ├── store.py            # upserts, quarantine, state
│   ├── reconcile.py
│   └── main.py             # one run, exit code = health
├── tests/
└── README.md

Tick each step as you finish it — your progress is saved in this browser only (back up or restore on the hub). Every code block has a copy button. If something goes wrong, the troubleshooting section at the end covers the usual suspects.

Phase 1

Stand up the customer's systems

A mock OAuth API and an SFTP server running locally that behave like the real thing, including expiring tokens.

  1. Create the project and environment.
    bash
    mkdir legacy-integration && cd legacy-integration && git init
    mkdir -p mocks sync tests
    uv init --app . && uv add fastapi uvicorn httpx paramiko
    uv add --dev pytest ruff
  2. Write the mock API: a token endpoint issuing tokens valid for 60 seconds, and a policies endpoint with cursor pagination and an updated_since filter.
    python
    # mocks/api.py
    import secrets
    import time
    
    from fastapi import FastAPI, Form, Header, HTTPException
    
    app = FastAPI()
    TOKENS: dict[str, float] = {}
    POLICIES = [{"id": f"POL-{i:05d}", "holder": f"Customer {i}", "premium": 100 + i,
                 "updated_at": f"2026-09-{1 + i % 28:02d}T10:00:00Z"} for i in range(1, 1001)]
    
    
    @app.post("/oauth/token")
    def token(grant_type: str = Form(...), client_id: str = Form(...), client_secret: str = Form(...)):
        if grant_type != "client_credentials" or client_secret != "s3cret":
            raise HTTPException(401, "invalid_client")
        t = secrets.token_hex(16)
        TOKENS[t] = time.time() + 60
        return {"access_token": t, "token_type": "Bearer", "expires_in": 60}
    
    
    @app.get("/policies")
    def policies(updated_since: str = "", cursor: int = 0, limit: int = 100,
                 authorization: str = Header("")):
        t = authorization.removeprefix("Bearer ")
        if TOKENS.get(t, 0) < time.time():
            raise HTTPException(401, "token expired or invalid")
        rows = [p for p in POLICIES if p["updated_at"] >= updated_since]
        page = rows[cursor:cursor + limit]
        nxt = cursor + limit if cursor + limit < len(rows) else None
        return {"items": page, "next_cursor": nxt}
  3. Write a Compose file that runs the API and an SFTP server with an upload folder.
    yaml
    # mocks/compose.yml
    services:
      api:
        image: python:3.12-slim
        working_dir: /app
        volumes: ["./:/app"]
        command: sh -c "pip install -q fastapi uvicorn python-multipart && uvicorn api:app --host 0.0.0.0 --port 8080"
        ports: ["8080:8080"]
      sftp:
        image: atmoz/sftp
        command: northwind:pass:::upload
        ports: ["2222:22"]
  4. Start the mocks and check both respond.
    bash
    docker compose -f mocks/compose.yml up -d
    curl -s -X POST localhost:8080/oauth/token \
      -d grant_type=client_credentials -d client_id=sync -d client_secret=s3cret
    Check: You receive a JSON token; sftp -P 2222 northwind@localhost logs in with password pass.
Phase 2

Configuration and authentication

Config from the environment with early failure, and a token cache that refreshes before expiry and once on 401.

  1. Write sync/config.py that loads API URL, client ID and secret, SFTP host, port, user and password, and the database path from environment variables, exiting with a clear list of anything missing.
    Reuse the load_config pattern from the Python delivery lesson. Put example values in .env.example, never real secrets in git.
  2. Create .env.example with placeholder values and load your real .env into the shell for local runs; add .env and *.db to .gitignore.
    bash
    cat > .env.example <<'ENV'
    API_URL=http://localhost:8080
    CLIENT_ID=sync
    CLIENT_SECRET=CHANGE_ME
    SFTP_HOST=localhost
    SFTP_PORT=2222
    SFTP_USER=northwind
    SFTP_PASSWORD=CHANGE_ME
    DB_PATH=sync.db
    ENV
    printf '.env\n*.db\n' >> .gitignore
    set -a && . ./.env && set +a
  3. Write the token cache.
    python
    # sync/auth.py
    import time
    
    import httpx
    
    from sync.config import CFG
    
    _cache = {"token": None, "exp": 0.0}
    
    
    def token(force: bool = False) -> str:
        if not force and _cache["token"] and time.time() < _cache["exp"] - 10:
            return _cache["token"]
        r = httpx.post(f"{CFG.api_url}/oauth/token", timeout=10, data={
            "grant_type": "client_credentials",
            "client_id": CFG.client_id, "client_secret": CFG.client_secret})
        r.raise_for_status()
        body = r.json()
        _cache.update(token=body["access_token"], exp=time.time() + body["expires_in"])
        return _cache["token"]
  4. Write a test with httpx.MockTransport or monkeypatching that proves a cached token is reused and a forced refresh fetches a new one.
    Check: uv run pytest -q passes.
Phase 3

Incremental API sync

Walk the API with cursors from the last watermark, retry once on 401, and upsert idempotently.

  1. Write the store: a policies table keyed by ID, a quarantine table, and a state table for watermarks and processed files.
    python
    # sync/store.py
    import sqlite3
    
    from sync.config import CFG
    
    db = sqlite3.connect(CFG.db_path)
    db.executescript("""
    CREATE TABLE IF NOT EXISTS policies(id TEXT PRIMARY KEY, holder TEXT, premium REAL, updated_at TEXT);
    CREATE TABLE IF NOT EXISTS claims(id TEXT PRIMARY KEY, policy_id TEXT, amount REAL, filed_on TEXT);
    CREATE TABLE IF NOT EXISTS quarantine(source TEXT, record TEXT, reason TEXT, at TEXT DEFAULT CURRENT_TIMESTAMP);
    CREATE TABLE IF NOT EXISTS state(key TEXT PRIMARY KEY, value TEXT);
    """)
    
    
    def get_state(key: str, default: str = "") -> str:
        row = db.execute("SELECT value FROM state WHERE key = ?", (key,)).fetchone()
        return row[0] if row else default
    
    
    def set_state(key: str, value: str) -> None:
        db.execute("INSERT INTO state VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value",
                   (key, value))
        db.commit()
  2. Write the policy sync: start from the stored watermark, page with cursors, refresh the token once on 401, validate and upsert, and advance the watermark only after the whole run succeeds.
    python
    # sync/policies.py
    import json
    
    import httpx
    
    from sync.auth import token
    from sync.config import CFG
    from sync.store import db, get_state, set_state
    
    
    def sync_policies() -> dict:
        since, cursor, written, bad, newest = get_state("policies_wm"), 0, 0, 0, ""
        with httpx.Client(base_url=CFG.api_url, timeout=30) as c:
            while cursor is not None:
                params = {"updated_since": since, "cursor": cursor, "limit": 200}
                r = c.get("/policies", params=params, headers={"Authorization": f"Bearer {token()}"})
                if r.status_code == 401:
                    r = c.get("/policies", params=params,
                              headers={"Authorization": f"Bearer {token(force=True)}"})
                r.raise_for_status()
                body = r.json()
                for p in body["items"]:
                    if not p.get("id", "").startswith("POL-") or p.get("premium", -1) < 0:
                        db.execute("INSERT INTO quarantine(source, record, reason) VALUES (?, ?, ?)",
                                   ("api", json.dumps(p), "invalid id or premium"))
                        bad += 1
                        continue
                    db.execute("""INSERT INTO policies VALUES (:id, :holder, :premium, :updated_at)
                                  ON CONFLICT(id) DO UPDATE SET holder=excluded.holder,
                                  premium=excluded.premium, updated_at=excluded.updated_at""", p)
                    written += 1
                    newest = max(newest, p["updated_at"])
                cursor = body["next_cursor"]
        db.commit()
        if newest:
            set_state("policies_wm", newest)          # only after a successful full run
        return {"written": written, "quarantined": bad}
    The watermark uses >= so the newest records are re-read next time; the upsert makes that harmless. Production code adds backoff on 429 and 5xx as in the integration lesson.
  3. Run it twice and confirm the second run writes only records at or after the watermark and creates no duplicates.
    bash
    uv run python -c "from sync.policies import sync_policies; print(sync_policies())"
    uv run python -c "from sync.policies import sync_policies; print(sync_policies())"
    sqlite3 sync.db 'SELECT COUNT(*), COUNT(DISTINCT id) FROM policies'
    Check: Both counts are 1000.
  4. Wait more than 60 seconds between two calls (or shorten the mock's expiry) to confirm the expired token is refreshed transparently.
    Check: The run succeeds and the mock logs one 401 followed by a new token request.
Phase 4

File drops over SFTP

Process each completed CSV exactly once, validate rows, quarantine failures and archive files.

  1. Create a sample claims file with a few deliberately bad rows and upload it with a .done marker.
    bash
    cat > claims-2026-10-01.csv <<'CSV'
    claim_id,policy_id,amount,filed_on
    CLM-1,POL-00001,250.00,2026-10-01
    CLM-2,POL-00002,-5,2026-10-01
    CLM-3,POL-99999,80.00,2026-10-01
    CLM-4,POL-00004,120.50,01/10/2026
    CSV
    touch claims-2026-10-01.csv.done
    uv run python - <<'PY'
    import paramiko
    t = paramiko.Transport(("localhost", 2222))
    t.connect(username="northwind", password="pass")
    sftp = paramiko.SFTPClient.from_transport(t)
    for f in ("claims-2026-10-01.csv", "claims-2026-10-01.csv.done"):   # data first, marker last
        sftp.put(f, f"upload/{f}")
    t.close()
    PY
    Upload the data file before its .done marker, exactly as a well-behaved sender would. Real integrations use key-based authentication with verified host keys, not passwords.
  2. Write the poller: list files with a matching .done marker, skip ones already in state, parse, validate each row (positive amount, ISO date, known policy), upsert valid claims, quarantine the rest with reasons, then record the file as processed and move it to an archive folder.
    python
    # sync/claims_files.py
    import csv
    import io
    import json
    from datetime import date
    
    import paramiko
    
    from sync.config import CFG
    from sync.store import db, get_state, set_state
    
    
    def reason(row: dict) -> str | None:
        try:
            if float(row["amount"]) <= 0:
                return "non-positive amount"
            date.fromisoformat(row["filed_on"])
        except ValueError:
            return "unparseable amount or date"
        if not db.execute("SELECT 1 FROM policies WHERE id = ?", (row["policy_id"],)).fetchone():
            return "unknown policy"
        return None
    
    
    def sync_claim_files() -> dict:
        t = paramiko.Transport((CFG.sftp_host, CFG.sftp_port))
        t.connect(username=CFG.sftp_user, password=CFG.sftp_password)
        sftp = paramiko.SFTPClient.from_transport(t)
        done = set(json.loads(get_state("claim_files", "[]")))
        stats = {"files": 0, "written": 0, "quarantined": 0}
        names = sftp.listdir("upload")
        for name in sorted(n for n in names if n.endswith(".csv") and n + ".done" in names):
            if name in done:
                continue
            with sftp.open(f"upload/{name}") as fh:
                rows = list(csv.DictReader(io.StringIO(fh.read().decode())))
            for row in rows:
                why = reason(row)
                if why:
                    db.execute("INSERT INTO quarantine(source, record, reason) VALUES (?, ?, ?)",
                               (name, json.dumps(row), why))
                    stats["quarantined"] += 1
                else:
                    db.execute("INSERT OR REPLACE INTO claims VALUES (?, ?, ?, ?)",
                               (row["claim_id"], row["policy_id"], float(row["amount"]), row["filed_on"]))
                    stats["written"] += 1
            db.commit()
            done.add(name)
            set_state("claim_files", json.dumps(sorted(done)))
            stats["files"] += 1
        t.close()
        return stats
  3. Run it twice: the first run writes one claim and quarantines three with reasons; the second run processes nothing.
    bash
    uv run python -c "from sync.claims_files import sync_claim_files; print(sync_claim_files())"
    sqlite3 sync.db 'SELECT reason, COUNT(*) FROM quarantine GROUP BY reason'
    Check: Quarantine shows non-positive amount, unknown policy and unparseable date, one each.
  4. Upload a file without its .done marker and confirm it is ignored until the marker arrives.
    Check: No new rows until you upload the marker.
Phase 5

Reconcile, report and run on a schedule

One command that runs everything, prints per-run counts as JSON, checks consistency and signals health through its exit code.

  1. Write a reconciliation that compares the API's total policy count (one cheap call) with the store, and fails if they differ.
    python
    # sync/reconcile.py
    import httpx
    
    from sync.auth import token
    from sync.config import CFG
    from sync.store import db
    
    
    def reconcile() -> dict:
        total, cursor = 0, 0
        with httpx.Client(base_url=CFG.api_url, timeout=30) as c:
            while cursor is not None:
                body = c.get("/policies", params={"cursor": cursor, "limit": 500},
                             headers={"Authorization": f"Bearer {token()}"}).json()
                total += len(body["items"])
                cursor = body["next_cursor"]
        stored = db.execute("SELECT COUNT(*) FROM policies").fetchone()[0]
        return {"source": total, "stored": stored, "ok": total == stored}
    A real API often offers a count endpoint or a report you can compare against instead of re-reading everything.
  2. Write sync/main.py that runs policies, claim files and reconciliation, prints one JSON line with all counts and timings, writes the last successful run time to state, and exits 1 if anything failed or reconciliation did not match.
    Check: uv run python -m sync.main; echo $? prints the JSON and 0.
  3. Add a staleness check: a tiny sync/health.py command that exits 1 if the last successful run recorded in state is older than 26 hours, so monitoring can alert even when the job silently stopped running.
    Check: Setting the stored timestamp to two days ago makes the command exit 1.
  4. Break it deliberately: delete ten policies from SQLite and rerun; reconciliation must report the mismatch and exit 1. Then run again (the next incremental sync will not fix deletions, so document how an operator triggers a full resync by clearing the watermark).
    Check: Exit code 1 and a clear 'source 1000, stored 990' message.
  5. Schedule it: a cron entry or a Kubernetes CronJob that runs nightly, with the exit code wired to an alert in whatever monitoring you use.
    yaml
    apiVersion: batch/v1
    kind: CronJob
    metadata:
      name: legacy-sync
    spec:
      schedule: "30 2 * * *"
      concurrencyPolicy: Forbid
      jobTemplate:
        spec:
          backoffLimit: 1
          template:
            spec:
              restartPolicy: Never
              containers:
                - name: sync
                  image: registry.example/legacy-sync:1.0.0
                  envFrom: [{secretRef: {name: legacy-sync-env}}]
    concurrencyPolicy: Forbid stops two runs overlapping and fighting over the watermark.
Phase 6

Hand it to an operator

Documentation and tests that let someone else run, monitor and fix the integration.

  1. Write tests for the row validator and for idempotency (running the same file twice writes the same rows).
    Check: uv run pytest -q passes.
  2. Write the README: what it syncs, configuration variables, how to run once, how to schedule, what the JSON output means, how to read the quarantine table, and runbooks for: token rejected, SFTP unreachable, reconciliation mismatch, full resync.
    Follow the runbook format from the handoff lesson.
  3. Record a short demo log (terminal session) showing the clean run, the no-duplicates re-run, the quarantine, the token refresh and the reconciliation failure, and commit it.
    bash
    script -q demo.log
    # ...run the scenarios...
    exit
    git add -A && git commit -m "Legacy integration: API + SFTP sync with quarantine and reconciliation"
  4. Tear down the mocks.
    bash
    docker compose -f mocks/compose.yml down -v
Help

Troubleshooting

The token endpoint returns 422 Unprocessable Entity
FastAPI's Form fields need the python-multipart package (installed in the mock's command) and the request must be form-encoded (data= in httpx, -d in curl), not JSON.
paramiko raises an authentication error
Check user, password and port 2222 match the sftp service command; for key-based setups ensure the key is mounted and permissions are 600.
Second run re-inserts all claims
The processed-files state is not being saved or read; check the state table and that set_state runs after commit.
Reconciliation mismatches right after a successful sync
Records may have changed between the sync and the count, or rows were quarantined; compare stored plus quarantined to source and document which counts should match.
A run overlaps with the previous one
Use concurrencyPolicy: Forbid in Kubernetes or a lock file with cron so two runs never move the watermark at once.
Next

Where to go from here

Did a step fail or feel unclear? Tell me which one →