How to Integrate CrewAI for lending with FastAPI for startups
Combining CrewAI for lending with FastAPI gives you a clean way to expose lending workflows as HTTP endpoints without turning your app into a monolith. You get an API layer for your startup’s product surface, plus an agent layer that can handle borrower intake, document review, affordability checks, and routing decisions.
This is the right pattern when you need to ship lending features fast, but still keep the orchestration logic isolated from your web tier.
Prerequisites
- •Python 3.10+
- •FastAPI installed
- •Uvicorn installed for local serving
- •CrewAI installed and configured for your lending agents
- •Access to your lender-specific tools or APIs:
- •credit bureau lookup
- •bank statement parsing
- •KYC/AML checks
- •underwriting rules engine
- •A
.envfile with any required keys for your agent tools - •Basic familiarity with
asyncPython and REST APIs
Integration Steps
- •
Install dependencies
Start by installing FastAPI, Uvicorn, and CrewAI.
pip install fastapi uvicorn crewai python-dotenv pydanticIf your lending workflow uses external tools, install those too. In practice, most startups also add HTTP clients and PDF parsers.
- •
Define your lending agent and tasks
CrewAI works best when you keep the agent responsibilities narrow. For lending, one agent can assess borrower data, another can validate documents, and a third can produce a recommendation.
from crewai import Agent, Task, Crew, Process lending_analyst = Agent( role="Lending Analyst", goal="Evaluate borrower applications and produce a lending recommendation", backstory=( "You analyze income, debt obligations, repayment history, " "and supporting documents for small business lending." ), verbose=True, allow_delegation=False, ) assess_application = Task( description=( "Review the applicant profile, cash flow summary, and credit indicators. " "Return a decision: approve, reject, or review manually." ), expected_output="A concise lending decision with reasons.", agent=lending_analyst, ) lending_crew = Crew( agents=[lending_analyst], tasks=[assess_application], process=Process.sequential, verbose=True, )This keeps the orchestration inside CrewAI while FastAPI stays focused on request handling.
- •
Build the FastAPI endpoint
Use FastAPI to accept borrower data and pass it into the crew execution path. The key method here is
Crew.kickoff(), which runs the workflow and returns the result.from fastapi import FastAPI from pydantic import BaseModel, Field from crewai import Agent, Task, Crew, Process app = FastAPI(title="Lending Orchestrator") class LendingRequest(BaseModel): applicant_name: str monthly_revenue: float = Field(gt=0) monthly_debt: float = Field(ge=0) credit_score: int = Field(ge=300, le=850) loan_amount: float = Field(gt=0) @app.post("/lending/review") async def review_lending_application(payload: LendingRequest): analyst = Agent( role="Lending Analyst", goal="Evaluate borrower applications and produce a lending recommendation", backstory="You assess startup loan applications.", verbose=False, allow_delegation=False, ) task = Task( description=( f"Applicant: {payload.applicant_name}\n" f"Monthly revenue: {payload.monthly_revenue}\n" f"Monthly debt: {payload.monthly_debt}\n" f"Credit score: {payload.credit_score}\n" f"Requested loan amount: {payload.loan_amount}\n\n" "Return a decision with risk notes." ), expected_output="Decision plus risk notes.", agent=analyst, ) crew = Crew( agents=[analyst], tasks=[task], process=Process.sequential, verbose=False, ) result = crew.kickoff() return {"application_id": payload.applicant_name.lower().replace(" ", "-"), "result": str(result)} - •
Add structured output for production use
In production you do not want raw text only. Wrap the response in a schema so downstream systems can consume it reliably.
from pydantic import BaseModel class LendingDecision(BaseModel): decision: str risk_level: str reason: str @app.post("/lending/review-structured", response_model=LendingDecision) async def review_structured(payload: LendingRequest): analyst = Agent( role="Lending Analyst", goal="Evaluate borrower applications and produce structured output", backstory="You return machine-readable lending decisions.", verbose=False, allow_delegation=False, ) task = Task( description=( f"Analyze this application and return JSON fields only:\n" f"decision, risk_level, reason\n\n" f"Applicant={payload.applicant_name}, " f"Revenue={payload.monthly_revenue}, " f"Debt={payload.monthly_debt}, " f"CreditScore={payload.credit_score}, " f"LoanAmount={payload.loan_amount}" ), expected_output="JSON with decision, risk_level, reason.", agent=analyst, ) crew = Crew(agents=[analyst], tasks=[task], process=Process.sequential) result = crew.kickoff() return LendingDecision( decision="review_manual", risk_level="medium", reason=str(result), ) - •
Run the API and wire in background processing if needed
If underwriting is slow because you call external services like credit bureaus or OCR tools, keep FastAPI responsive by pushing long-running work to background jobs or a queue. For simple setups you can start with Uvicorn.
uvicorn main:app --reload --port 8000
Testing the Integration
Use FastAPI’s TestClient to verify that your endpoint accepts input and returns a crew-generated response path.
from fastapi.testclient import TestClient
from main import app
client = TestClient(app)
response = client.post(
"/lending/review",
json={
"applicant_name": "Acme Logistics",
"monthly_revenue": 120000,
"monthly_debt": 25000,
"credit_score": 710,
"loan_amount": 50000,
},
)
print(response.status_code)
print(response.json())
Expected output:
200
{
"application_id": "acme-logistics",
"result": "...CrewAI assessment output..."
}
If you hit validation errors instead of a 200 response, check your Pydantic constraints first. Most integration issues come from bad request shapes before they ever reach CrewAI.
Real-World Use Cases
- •
Startup loan pre-screening
- •Expose an API that scores inbound applicants before sending them to human underwriters.
- •Useful when you want to reduce manual review volume early in the funnel.
- •
Document-driven underwriting
- •Combine FastAPI uploads with CrewAI agents that summarize bank statements, tax docs, and incorporation records.
- •Good fit for SMB lenders handling inconsistent document packages.
- •
Loan servicing triage
- •Route payment issues, covenant breaches, or refinancing requests into specialized agents.
- •Helps support teams classify cases before escalation.
If you want this pattern to hold up in production, keep FastAPI thin and make CrewAI responsible only for workflow logic. That separation makes it easier to swap models, add tools, or introduce human approval without rewriting your API surface.
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