Enterprise Integration for an AI App: One Adapter per Edge for SSO, the CRM, a Legacy CSV and Webhooks
A made-up customer, Acme Retail, has a company login, a CRM with its own field names, old orders in a nightly CSV and order.updated webhooks. Instead of rewiring the Support Copilot, put one small adapter at each edge: a token check, a chained order source and a signature check, with two tests per edge.
What you will learn
- Keep one Order shape inside the app and write one small adapter per customer system
- Chain a CRM source and a legacy CSV source behind one Protocol
- Verify an SSO token's signature, issuer, audience and expiry before serving data
- Accept a CRM webhook only when its HMAC SHA-256 signature matches
Before you start
- FastAPI Hello World: Routes, Uvicorn and Swagger
- Pydantic Request and Response Models
A forward deployed engineer fits the Support Copilot into a customer's company. The big idea is simple: you don't change the app for every customer. You put one small adapter at each edge. This lesson touches four edges: single sign-on, a CRM adapter, a legacy CSV export, and webhooks. The project is a small FastAPI app with its tests, and it runs without any API key. The project files are in the community, free to join.
Acme Retail's world
The customer is a made-up company called Acme Retail. They have four systems, and each one sends a different shape:
- Staff log in through the company single sign-on, so they arrive with a token, not a new password.
- Order data lives in their CRM, behind a REST API with its own field names, like
ordNoandamt_cents. - Older orders aren't in the CRM any more. They only exist in a nightly CSV export.
- The CRM pushes a message whenever an order changes. That's a webhook, called
order.updated.
Think of a new appliance taken to an old house. You don't rewire the house. You carry adapters, one per kind of socket: identity, data and events. Take the appliance to another house, and only the adapters change. A new customer means new adapters, not a new app.
app.py: the entry point
This is where everything is put together. The order source is a chain, CRM first and CSV archive second, and the order route depends on current_user, so every request stops at the SSO check before it reaches your code.
sso.configure(PUBLIC_PEM)
# In production: httpx.Client(base_url=ACME_CRM_URL, headers=...). Here the stand-in CRM answers.
source = ChainedSource(AcmeCrmSource(TestClient(crm)),
LegacyCsvSource(Path(__file__).parent / "data" / "orders_archive.csv"))
app = FastAPI(title="Support Copilot - Acme integration")
app.include_router(router)
@app.get("/orders/{order_id}")
def read_order(order_id: str, user: dict = Depends(sso.current_user)):
try:
order = source.get_order(order_id)
except OrderNotFound:
raise HTTPException(404, "order not found")
return {"requested_by": user["email"], "order": order.model_dump()}
The data edge: one shape, one interface
In sources.py, Order has just four fields, and everything inside the app talks about this shape only. OrderNotFound is the one error every source uses. And OrderSource is a Protocol: anything with a get_order method that returns an Order fits the same socket.
class Order(BaseModel):
id: str
email: str
amount: float
status: str
class OrderNotFound(Exception):
pass
class OrderSource(Protocol):
def get_order(self, order_id: str) -> Order: ...
The CRM adapter calls the CRM, which answers in its own words, and maps each field onto ours. Cents are divided by 100 and the state is lowercased. A 404 from the CRM becomes our own OrderNotFound. That mapping is the whole adapter.
class AcmeCrmSource:
"""Acme's CRM names the fields ordNo, cust_email, amt_cents and state."""
def __init__(self, client: httpx.Client):
self.client = client
def get_order(self, order_id: str) -> Order:
r = self.client.get(f"/crm/orders/{order_id}")
if r.status_code == 404:
raise OrderNotFound(order_id)
r.raise_for_status()
raw = r.json()
return Order(id=raw["ordNo"], email=raw["cust_email"],
amount=raw["amt_cents"] / 100, status=raw["state"].lower())
The old orders sit in a file, so LegacyCsvSource reads it row by row and builds the very same Order. If no row matches, it raises the same error, so a file source fails exactly like the CRM. ChainedSource then asks each source in turn:
class ChainedSource:
"""Try the CRM first, then the CSV archive."""
def __init__(self, *sources: OrderSource):
self.sources = sources
def get_order(self, order_id: str) -> Order:
for source in self.sources:
try:
return source.get_order(order_id)
except OrderNotFound:
continue
raise OrderNotFound(order_id)
Running the project's demo.py orders example: A-1001 comes from the CRM (12,999 cents becomes 129.99, SHIPPED becomes shipped), A-0412 isn't in the CRM so the CSV answers, and A-9999 is nowhere:
GET /orders/A-1001 -> 200 {"requested_by": "support@acme-retail.example", "order": {"id": "A-1001", "email": "asha@acme-retail.example", "amount": 129.99, "status": "shipped"}}
GET /orders/A-0412 -> 200 {"requested_by": "support@acme-retail.example", "order": {"id": "A-0412", "email": "meera@acme-retail.example", "amount": 89.5, "status": "delivered"}}
GET /orders/A-9999 -> 404 {"detail": "order not found"}
The app asks one question, and doesn't care which source answered. The same idea for an old system with no safe retry is in A Legacy System Adapter.
The identity edge: check the login token
The company SSO gives each staff member a token, and every request carries it. sso.py checks it before any data is served: the RS256 signature (did the real identity provider make it?), the issuer and the audience (is it from the right login system, and meant for this app?), and the expiry.
ISSUER = "https://sso.acme-retail.example"
AUDIENCE = "support-copilot"
bearer = HTTPBearer(auto_error=False)
def current_user(creds: HTTPAuthorizationCredentials | None = Depends(bearer)) -> dict:
if creds is None:
raise HTTPException(401, "missing token")
try:
return jwt.decode(creds.credentials, _public_key, algorithms=["RS256"],
issuer=ISSUER, audience=AUDIENCE,
options={"require": ["exp", "iss", "aud"]})
except jwt.ExpiredSignatureError:
raise HTTPException(401, "token expired")
except jwt.InvalidTokenError as err:
raise HTTPException(401, f"invalid token: {err}")
In production the public keys come from the identity provider's JWKS URL, for example Keycloak or Cognito. In the sample, a small key pair in idp.py plays the identity provider. The login example tries four tokens:
no token -> 401 {"detail": "missing token"}
expired token -> 401 {"detail": "token expired"}
wrong audience -> 401 {"detail": "invalid token: Audience doesn't match"}
good token -> 200 {"requested_by": "[email protected]", "order": {"id": "A-1001", ...}}
No valid token, no data. (The last line is shortened here; the full order is the same as above.)
The events edge: trust a webhook only if it's signed
A webhook is just a public URL, so anybody could post to it. The CRM and the app share a secret, the CRM signs the message body with HMAC SHA-256, and webhooks.py does the same calculation and compares:
SECRET = os.getenv("CRM_WEBHOOK_SECRET", "...").encode() # sample default shortened here
def sign(body: bytes) -> str:
return hmac.new(SECRET, body, hashlib.sha256).hexdigest()
@router.post("/webhooks/crm")
async def crm_webhook(request: Request, x_signature: str = Header(default="")):
body = await request.body()
if not hmac.compare_digest(sign(body), x_signature):
raise HTTPException(401, "bad signature")
event = json.loads(body)
return {"received": event["type"], "order": event["order"]["ordNo"]}
Change one word in the body after it was signed (delivered becomes refunded) and the signature no longer matches:
signed event -> 200 {"received": "order.updated", "order": "A-1001"}
tampered event -> 401 {"detail": "bad signature"}
The secret is read from the environment, with a sample default for the offline demo. In a real deployment it lives only in the environment, never in the code.
The tests: two per edge
test_integration.py has six tests: an order from the CRM and one from the legacy CSV; a missing token and an expired token, both 401; a good webhook (200) and a tampered one (401). All six pass, so every edge is checked.
A checklist for any customer
| Edge | Questions to ask | Your adapter |
|---|---|---|
| Identity | Which SSO? What are the issuer, the audience and the keys? | The token check |
| Data | Which API, which field names, and are there any files? | One source per system |
| Events | Which webhooks, and how are they signed? | The signature check |
| Secrets | Where are they kept? | In the environment, never in code |
| Logs | What may you log? | Order ids yes, personal data no |
For checking a design for missing authorization hops, see Authentication and Authorization Gaps.
Recap
| Piece | What it does |
|---|---|
Order + OrderSource | One shape inside the app, one socket every source fits |
AcmeCrmSource | Maps ordNo, cust_email, amt_cents, state onto the four fields |
LegacyCsvSource | Reads the nightly export, fails the same way |
ChainedSource | Asks each source in turn; 404 only when none has it |
current_user | RS256 signature, issuer, audience, expiry, or 401 |
crm_webhook | HMAC SHA-256 with compare_digest, or 401 |
Try it yourself
A second customer keeps orders in a different CRM whose API returns orderId, buyer, total (already in dollars) and status. Write its source class, and say which other files in the project would have to change.
Related course on Udemy
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)Related posts
Reading a Business Requirement Like an Architect: Function, Quality, Constraints and Assumptions
One sentence from an insurer's claims director becomes four buckets (function, quality, constraints, assumptions), two testable targets and five questions back to the business, before any design starts.
Discovery for an AI Project: Running the First Conversation, Five Question Groups and Three Red Flags
An insurance company says 'we would like an AI assistant'. That one sentence could be three different projects. Five question groups, asked to the right people, turn it into a one-page problem statement, and three red flags show what still blocks the design.
Communicating AI Decisions, Trade-offs and Risk to Executives: The Decision Card, the Risk Matrix and One Ask
A week before launch the CEO asks: is it safe to launch? Answer with a decision card that says what each option costs, a risk matrix where controls move a risk but never erase it, a one-page brief that ends with one ask, and an honest answer to 'can you guarantee it?'.
Feedback Loops, Expectations and SLAs for an AI Service: Find the Promise the Architecture Can't Keep
Two weeks after launch, the head of claims says 'I thought it never makes mistakes'. A weekly feedback loop, expectation gaps closed in writing, and a review of the draft SLA find the one clause nothing can measure before anyone signs it.
