How to Integrate FastAPI for fintech with LangChain for AI agents

By Cyprian AaronsUpdated 2026-04-21
fastapi-for-fintechlangchainai-agents

FastAPI gives you the HTTP layer for fintech workflows: account lookup, payment initiation, KYC checks, ledger writes, webhook handling. LangChain gives you the agent layer: tool selection, structured reasoning, and orchestration across those endpoints.

Put them together and you can build an AI agent that answers customer questions, triggers compliant backend actions, and routes requests to the right financial services without hardcoding every flow.

Prerequisites

  • Python 3.10+
  • A FastAPI app with at least one fintech endpoint exposed
  • A LangChain-compatible LLM provider configured with an API key
  • pip installed
  • Basic familiarity with:
    • fastapi.FastAPI
    • langchain.agents
    • langchain.tools
    • requests or httpx
  • A local .env file for secrets:
    • OPENAI_API_KEY
    • FINTECH_API_BASE_URL
    • any auth token your FastAPI service expects

Install the packages:

pip install fastapi uvicorn httpx langchain langchain-openai pydantic python-dotenv

Integration Steps

1) Expose your fintech capability in FastAPI

Start with a simple endpoint that returns account data. In production, this would call your core banking service or internal ledger.

from fastapi import FastAPI, Header, HTTPException
from pydantic import BaseModel

app = FastAPI(title="Fintech API")

class TransferRequest(BaseModel):
    from_account: str
    to_account: str
    amount: float
    currency: str = "USD"

@app.get("/accounts/{account_id}")
def get_account(account_id: str, x_api_key: str = Header(default="")):
    if x_api_key != "secret-fintech-key":
        raise HTTPException(status_code=401, detail="Unauthorized")

    return {
        "account_id": account_id,
        "status": "active",
        "balance": 12500.75,
        "currency": "USD"
    }

@app.post("/transfers")
def create_transfer(payload: TransferRequest, x_api_key: str = Header(default="")):
    if x_api_key != "secret-fintech-key":
        raise HTTPException(status_code=401, detail="Unauthorized")

    return {
        "transfer_id": "trf_12345",
        "status": "queued",
        "from_account": payload.from_account,
        "to_account": payload.to_account,
        "amount": payload.amount,
        "currency": payload.currency
    }

Run it:

uvicorn app:app --reload --port 8000

2) Wrap the FastAPI endpoints as LangChain tools

LangChain agents do best when each backend action is a tool with a clear contract. Use @tool so the agent can call your API through a typed function.

import os
import httpx
from langchain_core.tools import tool

FINTECH_API_BASE_URL = os.getenv("FINTECH_API_BASE_URL", "http://localhost:8000")
FINTECH_API_KEY = os.getenv("FINTECH_API_KEY", "secret-fintech-key")

@tool
def get_account_balance(account_id: str) -> str:
    """Fetch account details and balance from the fintech API."""
    headers = {"x-api-key": FINTECH_API_KEY}
    url = f"{FINTECH_API_BASE_URL}/accounts/{account_id}"

    response = httpx.get(url, headers=headers, timeout=10)
    response.raise_for_status()
    data = response.json()

    return (
        f"Account {data['account_id']} is {data['status']} "
        f"with balance {data['balance']} {data['currency']}"
    )

@tool
def initiate_transfer(from_account: str, to_account: str, amount: float) -> str:
    """Create a transfer request in the fintech API."""
    headers = {"x-api-key": FINTECH_API_KEY}
    url = f"{FINTECH_API_BASE_URL}/transfers"
    payload = {
        "from_account": from_account,
        "to_account": to_account,
        "amount": amount,
        "currency": "USD",
    }

    response = httpx.post(url, json=payload, headers=headers, timeout=10)
    response.raise_for_status()
    data = response.json()

    return f"Transfer {data['transfer_id']} created with status {data['status']}"

This is the clean boundary:

  • FastAPI owns business endpoints.
  • LangChain owns tool invocation.
  • The agent never talks directly to your database or core banking system.

3) Build the LangChain agent with those tools

Use a chat model and bind the tools into an agent executor. This lets the model decide when to fetch balances or initiate transfers.

from langchain_openai import ChatOpenAI
from langchain.agents import create_tool_calling_agent, AgentExecutor
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder

llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)

tools = [get_account_balance, initiate_transfer]

prompt = ChatPromptTemplate.from_messages([
    ("system", """You are a fintech operations assistant.
Use tools for any account lookup or transfer request.
Do not invent balances or transaction IDs."""),
    ("human", "{input}"),
    MessagesPlaceholder(variable_name="agent_scratchpad"),
])

agent = create_tool_calling_agent(llm=llm, tools=tools, prompt=prompt)
executor = AgentExecutor(agent=agent, tools=tools, verbose=True)

A few practical points:

  • Keep temperature at 0 for operational workflows.
  • Put compliance rules in the system prompt.
  • Never let the model fabricate financial state.

4) Call the agent from your FastAPI app

Now expose an AI endpoint in FastAPI that forwards user requests to the LangChain executor.

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI(title="AI Fintech Assistant")

class ChatRequest(BaseModel):
    message: str

@app.post("/agent/chat")
async def chat(payload: ChatRequest):
    result = await executor.ainvoke({"input": payload.message})
    return {"response": result["output"]}

That gives you one HTTP interface for both:

  • deterministic fintech APIs
  • agent-driven workflows on top of them

If you need auth propagation between layers, pass user context into the tool functions and enforce it before making any downstream call.

Testing the Integration

Use a direct invocation first. That isolates whether LangChain can reach your FastAPI service correctly.

import asyncio

async def main():
    result1 = await executor.ainvoke({
        "input": "Check balance for account ACC123"
    })
    print(result1["output"])

    result2 = await executor.ainvoke({
        "input": "Move 250 USD from ACC123 to ACC999"
    })
    print(result2["output"])

asyncio.run(main())

Expected output:

Account ACC123 is active with balance 12500.75 USD
Transfer trf_12345 created with status queued

If that fails:

  • verify FINTECH_API_BASE_URL
  • verify x-api-key
  • check your FastAPI server is running on the expected port
  • confirm your tool names match what the agent prompt expects

Real-World Use Cases

  • Customer support finance copilot

    • Answer balance questions.
    • Explain transaction status.
    • Trigger safe actions like card replacement or statement generation.
  • Ops assistant for payments teams

    • Create transfers.
    • Check settlement status.
    • Summarize failed webhook events and retry logic.
  • KYC and onboarding helper

    • Collect missing fields.
    • Route document verification requests.
    • Surface compliance flags before an application moves forward.

The pattern stays stable as you scale:

  • FastAPI exposes controlled financial actions.
  • LangChain decides which action to take.
  • Your agent stays auditable because every side effect goes through explicit endpoints.

Keep learning

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

Related Guides