How to Integrate CrewAI for fintech with FastAPI for multi-agent systems
Combining CrewAI for fintech with FastAPI gives you a clean way to expose multi-agent workflows as production APIs. The pattern is simple: CrewAI handles task orchestration across specialized agents, while FastAPI gives you the HTTP layer, validation, and deployment surface your fintech app needs.
This is useful when you need an endpoint that can route a customer request into multiple agent roles: fraud review, transaction summarization, compliance checks, or portfolio analysis. Instead of wiring those flows manually, you expose them through FastAPI and let CrewAI coordinate the work.
Prerequisites
- •Python 3.10+
- •A virtual environment set up
- •
crewai - •
fastapi - •
uvicorn - •
pydantic - •An LLM provider configured for CrewAI, such as OpenAI-compatible credentials
- •Basic familiarity with REST APIs and Python async/sync boundaries
Install the dependencies:
pip install crewai fastapi uvicorn pydantic
Set your model credentials in the environment:
export OPENAI_API_KEY="your-api-key"
Integration Steps
- •Define your request and response models
Keep your API contract explicit. In fintech, this matters because you want predictable inputs for things like transaction IDs, account metadata, or risk flags.
from pydantic import BaseModel, Field
from typing import Optional
class FintechAnalysisRequest(BaseModel):
customer_id: str = Field(..., examples=["cust_10291"])
transaction_id: str = Field(..., examples=["txn_88321"])
amount: float = Field(..., gt=0)
currency: str = Field(default="USD")
merchant_name: Optional[str] = None
class FintechAnalysisResponse(BaseModel):
summary: str
risk_level: str
recommended_action: str
- •Create specialized CrewAI agents
Use one agent per responsibility. For example, one agent summarizes the transaction context while another evaluates risk signals.
from crewai import Agent
transaction_analyst = Agent(
role="Transaction Analyst",
goal="Summarize transaction details and identify anomalies",
backstory="You analyze payment activity for fintech operations teams.",
verbose=True,
)
risk_analyst = Agent(
role="Risk Analyst",
goal="Assess whether a transaction should be flagged for review",
backstory="You specialize in fraud patterns, chargebacks, and suspicious payment behavior.",
verbose=True,
)
- •Define tasks and assemble the crew
CrewAI’s Task and Crew objects are what connect the agents into a workflow. The output from one task can inform the next task through shared context.
from crewai import Task, Crew, Process
transaction_task = Task(
description=(
"Analyze this transaction for operational context:\n"
"Customer ID: {customer_id}\n"
"Transaction ID: {transaction_id}\n"
"Amount: {amount} {currency}\n"
"Merchant: {merchant_name}"
),
expected_output="A concise summary of the transaction and any anomalies.",
agent=transaction_analyst,
)
risk_task = Task(
description=(
"Using the transaction summary, assess fraud risk and recommend an action.\n"
"Return risk_level as low, medium, or high."
),
expected_output="Risk level and recommended action.",
agent=risk_analyst,
)
crew = Crew(
agents=[transaction_analyst, risk_analyst],
tasks=[transaction_task, risk_task],
process=Process.sequential,
verbose=True,
)
- •Expose the workflow through FastAPI
This is where the integration becomes production-friendly. FastAPI handles input validation and exposes a /analyze endpoint that triggers the CrewAI workflow.
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
app = FastAPI(title="Fintech Multi-Agent API")
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
@app.post("/analyze", response_model=FintechAnalysisResponse)
def analyze_transaction(payload: FintechAnalysisRequest):
try:
result = crew.kickoff(inputs=payload.model_dump())
text = str(result)
return FintechAnalysisResponse(
summary=text,
risk_level="medium",
recommended_action="Review manually",
)
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
If you want stricter control over parsing, return structured JSON from your agents and map it into your response model instead of sending raw text back.
- •Run the API server
Use Uvicorn to serve the FastAPI app.
# save this file as main.py
# then run:
# uvicorn main:app --reload --host 0.0.0.0 --port 8000
For production deployments, remove --reload, pin worker count appropriately, and keep LLM timeouts tight.
Testing the Integration
Use curl or a small Python client to verify that the endpoint triggers the multi-agent flow.
import requests
payload = {
"customer_id": "cust_10291",
"transaction_id": "txn_88321",
"amount": 249.99,
"currency": "USD",
"merchant_name": "Northwind Electronics"
}
response = requests.post("http://localhost:8000/analyze", json=payload)
print(response.status_code)
print(response.json())
Expected output:
200
{
"summary": "Transaction analyzed by multiple agents ...",
"risk_level": "medium",
"recommended_action": "Review manually"
}
If you get a 500 error, check these first:
- •Your model credentials are set correctly
- •The agent/task definitions are valid Python objects
- •The request payload matches the Pydantic schema
- •Your LLM provider is reachable from the runtime environment
Real-World Use Cases
- •
Fraud triage API
Route suspicious card or ACH transactions through agents that summarize activity, score risk, and recommend escalation. - •
KYC/AML support service
Build an endpoint that reviews onboarding data across multiple agents for identity gaps, sanctions signals, and policy violations. - •
Customer dispute assistant
Accept dispute details and have one agent reconstruct transaction history while another drafts a resolution recommendation for ops teams.
The clean pattern here is straightforward: FastAPI owns request handling; CrewAI owns reasoning orchestration. That separation makes it easier to test each layer independently and keeps your fintech agent system maintainable when requirements get stricter.
Keep learning
- •The complete AI Agents Roadmap — my full 8-step breakdown
- •Free: The AI Agent Starter Kit — PDF checklist + starter code
- •Work with me — I build AI for banks and insurance companies
By Cyprian Aarons, AI Consultant at Topiax.
Want the complete 8-step roadmap?
Grab the free AI Agent Starter Kit — architecture templates, compliance checklists, and a 7-email deep-dive course.
Get the Starter Kit