How to Integrate FastAPI for healthcare with PostgreSQL for AI agents

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

FastAPI for healthcare gives you a clean API layer for clinical workflows, while PostgreSQL gives your agent system durable state, auditability, and queryable patient or claim data. Put them together and you get an AI agent backend that can accept requests from clinicians or ops teams, store structured health data safely, and retrieve context fast enough for decision support.

Prerequisites

  • Python 3.10+
  • A running PostgreSQL instance
  • A FastAPI app scaffolded with uvicorn
  • Database driver:
    • psycopg or psycopg[binary]
  • FastAPI dependencies:
    • fastapi
    • pydantic
    • uvicorn
  • Environment variables configured:
    • DATABASE_URL=postgresql://user:password@localhost:5432/healthcare_ai
  • Basic understanding of:
    • REST endpoints
    • SQL schema design
    • async Python

Integration Steps

  1. Install the dependencies
pip install fastapi uvicorn psycopg[binary] pydantic

This is the minimum stack for a production-style integration. If you want connection pooling later, add psycopg_pool.

  1. Create a PostgreSQL connection layer

Use one place to manage DB access. For AI agents, this keeps retrieval and write operations predictable and easy to test.

import os
import psycopg
from psycopg.rows import dict_row

DATABASE_URL = os.getenv("DATABASE_URL")

def get_connection():
    return psycopg.connect(DATABASE_URL, row_factory=dict_row)

def init_db():
    with get_connection() as conn:
        with conn.cursor() as cur:
            cur.execute("""
                CREATE TABLE IF NOT EXISTS patient_events (
                    id SERIAL PRIMARY KEY,
                    patient_id TEXT NOT NULL,
                    event_type TEXT NOT NULL,
                    payload JSONB NOT NULL,
                    created_at TIMESTAMPTZ DEFAULT NOW()
                )
            """)
        conn.commit()

That table is enough for agent memory around encounters, triage events, lab results, or claim actions.

  1. Build the FastAPI healthcare endpoint

FastAPI’s @app.post() route decorator and dependency injection make it straightforward to expose clinical workflows as API endpoints.

from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from typing import Any, Dict

app = FastAPI(title="Healthcare AI Agent API")

class PatientEventIn(BaseModel):
    patient_id: str
    event_type: str
    payload: Dict[str, Any]

@app.on_event("startup")
def startup():
    init_db()

@app.post("/patient-events")
def create_patient_event(event: PatientEventIn):
    try:
        with get_connection() as conn:
            with conn.cursor() as cur:
                cur.execute(
                    """
                    INSERT INTO patient_events (patient_id, event_type, payload)
                    VALUES (%s, %s, %s)
                    RETURNING id, patient_id, event_type, payload, created_at
                    """,
                    (event.patient_id, event.event_type, event.payload),
                )
                row = cur.fetchone()
            conn.commit()
        return row
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

This endpoint gives your agent system a write path for clinical context. In a real deployment, add auth, request validation rules, and PHI controls before exposing it.

  1. Add a retrieval endpoint for the agent

Your agent needs context before it can reason. Querying PostgreSQL by patient ID and event type is the simplest reliable pattern.

from typing import List

@app.get("/patient-events/{patient_id}")
def list_patient_events(patient_id: str) -> List[dict]:
    with get_connection() as conn:
        with conn.cursor() as cur:
            cur.execute(
                """
                SELECT id, patient_id, event_type, payload, created_at
                FROM patient_events
                WHERE patient_id = %s
                ORDER BY created_at DESC
                LIMIT 20
                """,
                (patient_id,),
            )
            rows = cur.fetchall()
    return rows

For AI agents this becomes the memory layer: fetch recent events, summarize them in the model prompt, then decide what action to take.

  1. Call the API from an agent workflow

If your agent runs outside FastAPI — for example in a worker or orchestration service — use the API as the contract and PostgreSQL as persistence behind it.

import requests

base_url = "http://localhost:8000"

payload = {
    "patient_id": "P-10293",
    "event_type": "lab_result",
    "payload": {
        "test": "HbA1c",
        "value": 8.4,
        "unit": "%",
        "flag": "high"
    }
}

create_resp = requests.post(f"{base_url}/patient-events", json=payload)
print(create_resp.status_code)
print(create_resp.json())

read_resp = requests.get(f"{base_url}/patient-events/P-10293")
print(read_resp.status_code)
print(read_resp.json())

That gives your agent a simple loop:

  • write new observations to Postgres through FastAPI
  • read prior context when deciding next steps

Testing the Integration

Run the app:

uvicorn main:app --reload --port 8000

Then verify both write and read paths:

import requests

event = {
    "patient_id": "P-2048",
    "event_type": "triage_note",
    "payload": {
        "symptoms": ["fever", "cough"],
        "severity": "moderate"
    }
}

r1 = requests.post("http://localhost:8000/patient-events", json=event)
print("CREATE:", r1.status_code)

r2 = requests.get("http://localhost:8000/patient-events/P-2048")
print("READ:", r2.status_code)
print(r2.json())

Expected output:

CREATE: 200
READ: 200
[{'id': 1, 'patient_id': 'P-2048', 'event_type': 'triage_note', 'payload': {'symptoms': ['fever', 'cough'], 'severity': 'moderate'}, 'created_at': '2026-04-21T...'}]

If you get rows back from PostgreSQL through FastAPI, the integration is working.

Real-World Use Cases

  • Clinical intake agents

    • Capture symptoms from chat or voice intake.
    • Store structured notes in PostgreSQL.
    • Let the agent retrieve history before escalating to a clinician.
  • Prior authorization assistants

    • Track payer requirements and submitted documents.
    • Persist every decision and timestamp in PostgreSQL.
    • Expose status updates through FastAPI endpoints.
  • Care coordination copilots

    • Aggregate recent labs, medications, and visit summaries.
    • Use PostgreSQL as the source of truth for agent memory.
    • Serve recommendations through a healthcare API layer built with FastAPI.

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