Education › Forward Deployed › Stage 3: Building & integrating

Integrating with enterprise systems

APIs, OAuth and service accounts, webhooks, files over SFTP, databases and legacy SOAP — with idempotency and retries.

Intermediate ~45 min read Module 9 of 20

An FDE's software is only as useful as its connections to the customer's systems. In a single engagement you may call a modern REST API with OAuth, receive webhooks, pick up nightly CSV files from an SFTP server, read incrementally from a database, and talk to a SOAP service older than some of your colleagues. This lesson covers each of those integration styles, the machine-to-machine authentication patterns that go with them, and the reliability patterns that keep integrations correct when networks fail and messages repeat: idempotency, incremental sync with watermarks, quarantines and reconciliation.

After this module you can
  • Authenticate service-to-service with OAuth client credentials, API keys and mTLS
  • Consume paginated, rate-limited APIs safely
  • Receive webhooks securely with signature verification and idempotent handling
  • Integrate file drops over SFTP and incremental database reads robustly
  • Apply idempotency, watermarks, dead-letter queues and reconciliation

Machine-to-machine authentication

Integrations run without a person present, so they authenticate as a machine identity. The customer's identity team will usually tell you which pattern they allow; know them all.

PatternHow it worksWatch out for
OAuth 2.0 client credentialsExchange client ID and secret for a short-lived access token at the token endpointCache tokens until near expiry; request minimal scopes
API keyStatic secret sent in a headerRotation, storage in a vault, never in URLs
Mutual TLS (mTLS)Client presents a certificate the server trustsCertificate renewal before expiry
Workload identityCloud or Kubernetes identity federated to the targetBest option when available: no static secret
Signed requestsRequest signed with a shared secret or key (HMAC)Clock skew and canonicalisation details
OAuth client credentials with token caching
python
import os
import time

import httpx

_token = {"value": None, "expires": 0.0}


def access_token() -> str:
    if _token["value"] and time.time() < _token["expires"] - 60:
        return _token["value"]
    r = httpx.post(os.environ["TOKEN_URL"], timeout=10, data={
        "grant_type": "client_credentials",
        "client_id": os.environ["CLIENT_ID"],
        "client_secret": os.environ["CLIENT_SECRET"],
        "scope": "claims.read",
    })
    r.raise_for_status()
    body = r.json()
    _token.update(value=body["access_token"], expires=time.time() + body["expires_in"])
    return _token["value"]

Consuming APIs: pagination and rate limits

Enterprise APIs return data in pages and limit how fast you may call them. Prefer cursor (or token) pagination, which stays correct when records change during the read, over page-number pagination, which can skip or repeat records. Respect rate limits: read Retry-After on 429 responses, back off, and keep concurrency low until you know the limits. A runaway integration that overloads a customer system is a fast way to lose access.

Walk a cursor-paginated endpoint
python
def fetch_all(client, path: str, page_size: int = 200):
    cursor = None
    while True:
        params = {"limit": page_size, **({"cursor": cursor} if cursor else {})}
        r = client.get(path, params=params,
                       headers={"Authorization": f"Bearer {access_token()}"})
        if r.status_code == 429:
            time.sleep(int(r.headers.get("Retry-After", "5")))
            continue
        r.raise_for_status()
        body = r.json()
        yield from body["items"]
        cursor = body.get("next_cursor")
        if not cursor:
            break

Webhooks: receiving events safely

With webhooks, the customer's system calls you when something happens. Three rules keep them safe and correct. Verify every request's signature (usually an HMAC of the raw body with a shared secret) and reject anything unsigned or old. Respond quickly (within a few seconds) with 2xx and process asynchronously, because senders time out and retry. And make processing idempotent, because senders deliver at least once and duplicates are normal.

Verify an HMAC-signed webhook before trusting it
python
import hashlib
import hmac
import os
import time

SECRET = os.environ["WEBHOOK_SECRET"].encode()


def verify(raw_body: bytes, signature_hex: str, timestamp: str, max_age_s: int = 300) -> bool:
    if abs(time.time() - int(timestamp)) > max_age_s:
        return False                                   # reject replays of old requests
    expected = hmac.new(SECRET, timestamp.encode() + b"." + raw_body, hashlib.sha256).hexdigest()
    return hmac.compare_digest(expected, signature_hex)  # constant-time comparison

Each provider documents its own header names and signing format; follow it exactly, and always sign over the raw bytes, not re-serialised JSON. Store the event ID of every processed event and skip ones you have seen.

Files and databases

Plenty of enterprise data still moves as files: nightly CSV or XML exports dropped on an SFTP server. Robust file integrations agree a naming convention, wait for a completion signal (a .done marker file or an atomic rename) so you never read a half-written file, verify a checksum or row count, process each file exactly once by recording processed file names, and move processed files to an archive folder rather than deleting them.

For databases, read from a replica or reporting view, never hammer the primary, and read incrementally using a watermark: the highest updated_at (or a monotonically increasing ID) you have processed. Overlap the window slightly to catch late commits, and dedupe on the primary key. Where the customer supports it, change data capture (CDC) streams inserts, updates and deletes from the database log and catches deletes that watermarks miss.

Incremental read with a watermark and a safety overlap
sql
-- :last_watermark is the max(updated_at) from the previous successful run
SELECT claim_id, status, amount, updated_at
FROM claims_view
WHERE updated_at >= :last_watermark - INTERVAL '10 minutes'
ORDER BY updated_at, claim_id;
-- upsert by claim_id on the target, then store the new max(updated_at)
Note

Legacy SOAP services are still common in insurance, banking and government. Python's zeep library reads the WSDL and generates callable operations; treat the service like any other API with timeouts, retries and logging.

Patterns that keep integrations correct

  • Idempotency: every write keyed so repeating it has no extra effect (upserts, idempotency keys, processed-event tables).
  • At-least-once with dedupe beats chasing exactly-once delivery: accept duplicates and make them harmless.
  • Quarantine / dead-letter queue: records or events that fail validation go somewhere visible with the reason, instead of blocking the pipeline or vanishing.
  • Watermarks stored only after success, so a failed run re-reads rather than skips.
  • Reconciliation: periodically compare counts or totals between source and target and alert on drift.
  • Contract tests: a test that checks the shape of the partner's responses, so you notice when they change.
  • Observability: per-run counts (read, written, quarantined), last success time and lag, with alerts.
SOURCESrecordsvalidinvalidcompareREST APIOAuth, cursorsWebhooksHMAC verifiedSFTP files.done markersDatabasewatermark / CDCValidate, upsertidempotentTarget storeQuarantinewith reasonsReconcilecounts vs source
Every integration style feeds the same reliable core: validate, upsert idempotently, quarantine failures, record watermarks only after success, and reconcile against the source.
Hands-on practice

Three integrations, one reliable store

  1. Run a mock OAuth token endpoint and paginated API locally (a small FastAPI app) that issues tokens expiring in 60 seconds and returns cursor pages.
  2. Implement the token cache and cursor walker, and upsert results into SQLite by ID; confirm a second run creates no duplicates.
  3. Add a webhook endpoint that verifies an HMAC signature and timestamp, returns 202 immediately, and records event IDs to skip duplicates; replay the same event twice.
  4. Run an SFTP server container, drop CSV files with .done markers, and write a poller that processes each file once and archives it.
  5. Add a quarantine table for rows that fail validation, with the reason, and print per-run counts.
  6. Write a reconciliation query comparing source and target counts and make the job exit non-zero on mismatch.
Cheat sheet

Integrating with enterprise systems — at a glance

Main things to focus on

  • Machine identity: client credentials, API keys, mTLS, or workload identity (best).
  • Cursor pagination, respect Retry-After, low concurrency until limits are known.
  • Webhooks: verify signature and age, respond fast, process idempotently.
  • Files: completion markers, checksums, process once, archive.
  • Databases: replica or view, incremental watermarks with overlap, or CDC.
  • Idempotency, quarantine, reconciliation and per-run metrics everywhere.

Auth

grant_type=client_credentialsOAuth machine-to-machine token
cache token until expires_in - 60sAvoid a token call per request
Authorization: Bearer TOKENSend the token
mTLS: client cert + key, server trusts CACertificate-based identity

APIs

?limit=N&cursor=CCursor pagination
429 + Retry-AfterBack off as instructed
Idempotency-Key headerSafe retries for POSTs
contract test on response shapeDetect partner changes

Webhooks

HMAC-SHA256(secret, ts + '.' + raw_body)Typical signature scheme
hmac.compare_digestConstant-time comparison
reject if |now - ts| > 300sReplay protection
202 then queueRespond fast, process async

Files and DBs

FILE.csv + FILE.csv.doneCompletion marker
processed_files tableProcess each file once
WHERE updated_at >= wm - overlapIncremental read
CDCStream inserts, updates and deletes

Common pitfalls

  • Fetching a new OAuth token for every request.
  • Page-number pagination over changing data, skipping or repeating records.
  • Processing webhooks synchronously and timing out, causing retries and duplicates.
  • Reading files while they are still being written.
  • Advancing the watermark before the write succeeded.
Quiz

Check your understanding

5 questions · 4 to pass · answers are explained as you go. Your best score is saved on this device only.

Progress and quiz scores are saved in this browser only. Back up or restore on the hub.

Was this lesson useful? Tell me what to improve →