How to Integrate CrewAI for lending with FastAPI for AI agents
Combining CrewAI for lending with FastAPI gives you a clean way to expose lending workflows as HTTP APIs. That means you can take multi-step agent logic — borrower screening, document checks, risk summarization, and decision support — and make it callable from internal systems, underwriting portals, or orchestration layers.
The pattern is simple: CrewAI handles the agent workflow, FastAPI handles request/response plumbing. The result is an API surface your product teams can consume without knowing anything about agent internals.
Prerequisites
- •Python 3.10+
- •
fastapi - •
uvicorn - •
crewai - •Access to your LLM provider configured in environment variables
- •A lending use case defined:
- •loan application review
- •borrower risk summary
- •document extraction and validation
- •Basic familiarity with:
- •Pydantic models
- •REST endpoints
- •async Python
Install the packages:
pip install fastapi uvicorn crewai pydantic
Set your model key before running the app:
export OPENAI_API_KEY="your-api-key"
Integration Steps
- •Define the lending task and agent
Start by creating a CrewAI agent that understands lending operations. Keep the scope narrow: one agent per job is easier to test and reason about.
from crewai import Agent, Task, Crew, Process
loan_underwriter = Agent(
role="Loan Underwriter",
goal="Review loan applications and produce a concise lending risk summary",
backstory=(
"You are a senior lending analyst who evaluates borrower profiles, "
"income stability, debt burden, and document completeness."
),
verbose=True,
allow_delegation=False,
)
loan_review_task = Task(
description=(
"Review this loan application data and return a structured risk summary: {application_data}. "
"Include red flags, missing fields, and a recommendation."
),
expected_output="A short underwriting summary with recommendation and risks",
agent=loan_underwriter,
)
- •Wrap the CrewAI workflow in a service function
This function becomes the bridge between HTTP requests and the agent runtime. It builds the crew, runs it, and returns plain text or structured output.
def run_loan_review(application_data: dict) -> str:
crew = Crew(
agents=[loan_underwriter],
tasks=[loan_review_task],
process=Process.sequential,
verbose=True,
)
result = crew.kickoff(inputs={"application_data": application_data})
return str(result)
If you want stricter output contracts, define a Pydantic model and instruct the task to emit JSON. That makes downstream validation much easier.
- •Create a FastAPI endpoint
Now expose the workflow through FastAPI. Use request models so your API stays explicit and easy to validate.
from fastapi import FastAPI
from pydantic import BaseModel, Field
app = FastAPI(title="Lending Agent API")
class LoanApplication(BaseModel):
applicant_name: str = Field(..., examples=["Jane Doe"])
income: float
monthly_debt: float
credit_score: int
employment_status: str
requested_amount: float
class ReviewResponse(BaseModel):
summary: str
@app.post("/loan/review", response_model=ReviewResponse)
def review_loan(application: LoanApplication):
application_data = application.model_dump()
summary = run_loan_review(application_data)
return ReviewResponse(summary=summary)
- •Add error handling around the agent call
Agent calls can fail for model errors, timeouts, or malformed outputs. Handle that at the API boundary so clients get predictable responses.
from fastapi import HTTPException
@app.post("/loan/review-safe", response_model=ReviewResponse)
def review_loan_safe(application: LoanApplication):
try:
summary = run_loan_review(application.model_dump())
return ReviewResponse(summary=summary)
except Exception as exc:
raise HTTPException(
status_code=500,
detail=f"Loan review failed: {str(exc)}"
)
For production systems, log the raw exception server-side and return a stable error message to clients.
- •Run the API server
Use Uvicorn to serve FastAPI locally.
uvicorn main:app --reload --host 0.0.0.0 --port 8000
If you split code into modules, keep the FastAPI app in one entrypoint file and isolate CrewAI logic in a service module. That keeps your route layer thin.
Testing the Integration
Send a test request with curl or Python requests.
import requests
payload = {
"applicant_name": "Jane Doe",
"income": 85000,
"monthly_debt": 1200,
"credit_score": 710,
"employment_status": "full-time",
"requested_amount": 25000,
}
response = requests.post("http://localhost:8000/loan/review", json=payload)
print(response.status_code)
print(response.json())
Expected output will look like this:
{
"summary": "Applicant shows moderate risk. Credit score is acceptable, income supports repayment capacity, but debt-to-income ratio should be reviewed further. Recommendation: proceed with manual underwriting."
}
If you get a 422 response from FastAPI, your request body does not match the Pydantic schema. If you get a 500 response, inspect the CrewAI task output format or model configuration first.
Real-World Use Cases
- •
Loan pre-screening API
- •Expose an endpoint that scores incoming applications before they reach human underwriters.
- •Useful for routing low-risk cases automatically and flagging edge cases.
- •
Document review assistant
- •Combine OCR output with CrewAI to validate pay stubs, bank statements, and ID documents.
- •FastAPI becomes the interface for document upload pipelines.
- •
Underwriting copilot
- •Build an internal tool where analysts submit borrower data and receive a structured risk brief.
- •This works well when you need consistent summaries across many analysts.
The main design rule is to keep FastAPI responsible for transport and validation, while CrewAI owns reasoning and workflow execution. Once you separate those concerns cleanly, it becomes much easier to extend from one lending endpoint to an entire agent-driven decision platform.
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