How to Integrate CrewAI for fintech with FastAPI for startups
Combining CrewAI for fintech with FastAPI gives you a clean way to expose agent workflows as production HTTP endpoints. For startups, that usually means turning a multi-step finance assistant into a backend service that can triage loan requests, summarize transaction risk, or route compliance checks without wiring everything into one monolith.
Prerequisites
- •Python 3.10+
- •
fastapi - •
uvicorn - •
crewai - •
pydantic - •An API key for your LLM provider
- •A local or deployed FastAPI project structure
- •Basic familiarity with async HTTP APIs and agent orchestration
Install the dependencies:
pip install fastapi uvicorn crewai pydantic
Integration Steps
- •
Define your fintech agent and task
Start by creating a CrewAI agent that handles one finance-specific job. Keep the scope tight: credit memo summarization, KYC review, transaction anomaly analysis, or customer support triage.
from crewai import Agent, Task, Crew, Process
fintech_analyst = Agent(
role="Fintech Risk Analyst",
goal="Analyze customer financial data and produce a concise risk summary",
backstory="You work for a startup that automates lending and compliance workflows.",
verbose=True,
)
risk_task = Task(
description=(
"Review the provided financial profile and identify key risk signals, "
"missing data, and recommended next actions."
),
expected_output="A short structured risk assessment with recommendations.",
agent=fintech_analyst,
)
- •
Wrap the CrewAI workflow in a service function
This keeps your FastAPI layer thin. The endpoint should call one function that creates the crew and runs it.
from crewai import Crew, Process
def run_risk_analysis(profile_text: str) -> str:
crew = Crew(
agents=[fintech_analyst],
tasks=[risk_task],
process=Process.sequential,
verbose=True,
)
result = crew.kickoff(inputs={"profile_text": profile_text})
return str(result)
- •
Expose the workflow through FastAPI
Use Pydantic models for request validation. This is where startup-grade API hygiene matters: validate input, keep response shapes stable, and return predictable JSON.
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI(title="Fintech Agent API")
class RiskRequest(BaseModel):
profile_text: str
class RiskResponse(BaseModel):
analysis: str
@app.post("/analyze-risk", response_model=RiskResponse)
def analyze_risk(payload: RiskRequest):
analysis = run_risk_analysis(payload.profile_text)
return RiskResponse(analysis=analysis)
- •
Run the app and wire it to your internal systems
Start Uvicorn locally first. In production, place this behind an API gateway or load balancer and add auth before exposing it to other services.
# save as main.py
# then run:
# uvicorn main:app --reload --host 0.0.0.0 --port 8000
If you need the endpoint to accept structured fintech inputs instead of free text, define explicit fields:
class CustomerProfile(BaseModel):
customer_id: str
monthly_income: float
monthly_debt: float
delinquencies_last_12m: int
@app.post("/score-customer")
def score_customer(profile: CustomerProfile):
prompt = (
f"Customer ID: {profile.customer_id}\n"
f"Monthly income: {profile.monthly_income}\n"
f"Monthly debt: {profile.monthly_debt}\n"
f"Delinquencies last 12 months: {profile.delinquencies_last_12m}"
)
result = run_risk_analysis(prompt)
return {"customer_id": profile.customer_id, "result": result}
- •
Add basic error handling before shipping
Crew-based workflows can fail due to model errors, bad inputs, or timeouts. Catch exceptions at the boundary and return usable API responses.
from fastapi import HTTPException
@app.post("/analyze-risk-safe", response_model=RiskResponse)
def analyze_risk_safe(payload: RiskRequest):
try:
analysis = run_risk_analysis(payload.profile_text)
return RiskResponse(analysis=analysis)
except Exception as exc:
raise HTTPException(status_code=500, detail=f"Agent execution failed: {exc}")
Testing the Integration
Use curl or FastAPI’s interactive docs to verify the endpoint works.
curl -X POST "http://127.0.0.1:8000/analyze-risk" \
-H "Content-Type: application/json" \
-d '{"profile_text":"Applicant has stable income but two late payments in the last 6 months."}'
Expected output:
{
"analysis": "The applicant shows moderate risk due to recent late payments, but stable income is a positive signal. Recommend manual review and verification of payment history."
}
If you want a quick programmatic test:
import requests
resp = requests.post(
"http://127.0.0.1:8000/analyze-risk",
json={"profile_text": "High card utilization with recurring overdrafts."},
)
print(resp.status_code)
print(resp.json())
Real-World Use Cases
- •
Loan pre-screening
- •Use CrewAI agents to summarize applicant profiles and FastAPI to expose the scoring endpoint to your underwriting platform.
- •
Fraud triage
- •Send suspicious transaction metadata into an agent workflow that produces a human-readable fraud rationale for analysts.
- •
Compliance support
- •Build endpoints that classify KYC/AML cases, extract missing documents, and generate reviewer notes for operations teams.
The pattern is simple: keep CrewAI focused on reasoning, keep FastAPI focused on transport and validation. That separation makes the system easier to test, easier to secure, and easier to scale when your startup starts getting real traffic.
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