Datalumina

Database

Upload API

Give every request its own SQLAlchemy session, then upload intake notes, list contracts, and read one.

By the end of this page you can upload intake notes over HTTP, list every contract, and read one by its ID.

SQLAlchemy writes the SQL for you. session.add() inserts a contract, session.get() reads one by its ID, and select() builds the list. FastAPI checks the request body before your code runs.

Open a session per request

Replace backend/app/db.py. The highlighted lines are new.

backend/app/db.py
from datetime import datetime
from typing import Annotated

from fastapi import Depends
from sqlalchemy import DateTime, create_engine, func
from sqlalchemy.dialects.postgresql import JSONB
from sqlalchemy.orm import DeclarativeBase, Mapped, Session, mapped_column, sessionmaker

from app.config import settings

engine = create_engine(settings.database_url)
new_session = sessionmaker(engine, expire_on_commit=False)  # Objects keep values after commit.


class Base(DeclarativeBase):
    # Dicts and lists are stored as JSONB, datetimes with their time zone.
    type_annotation_map = {dict: JSONB, list: JSONB, datetime: DateTime(timezone=True)}


class Contract(Base):
    __tablename__ = "contracts"

    id: Mapped[int] = mapped_column(primary_key=True)
    title: Mapped[str]
    notes: Mapped[str]
    # pending, processing, needs_review, failed, drafted, sent, signed
    status: Mapped[str] = mapped_column(server_default="pending")
    reason: Mapped[str | None]  # why it needs review, or the error
    contract_type: Mapped[str | None]  # fixed_price, retainer, discovery, none
    fields: Mapped[dict | None]  # LLM step 1: client, price, dates
    sections: Mapped[list] = mapped_column(server_default="[]")  # LLM step 2: one dict each
    token: Mapped[str | None] = mapped_column(unique=True)  # the signing link
    content_hash: Mapped[str | None]  # SHA-256 of the document at Send
    sent_at: Mapped[datetime | None]
    signer: Mapped[dict | None]  # name, initials, user agent
    signed_at: Mapped[datetime | None]
    pdf: Mapped[bytes | None] = mapped_column(deferred=True)  # loaded only when asked for
    created_at: Mapped[datetime] = mapped_column(server_default=func.now())

    def as_dict(self) -> dict:  # Every column except the PDF, for the API.
        return {c.name: getattr(self, c.name) for c in self.__table__.columns if c.name != "pdf"}


def get_session():
    with new_session() as session:  # One session per request, closed after the response.
        yield session


SessionDep = Annotated[Session, Depends(get_session)]

A session is one conversation with the database. get_session() is a FastAPI dependency. It opens a session for each request and closes it after the response, and SessionDep is the type a route asks for to get one.

expire_on_commit=False keeps the values on an object after commit(), so the code can still read them without another query. as_dict() turns a contract into a dict for the JSON response and leaves out the PDF.

Add the routes

Replace backend/app/main.py.

backend/app/main.py
from contextlib import asynccontextmanager

from fastapi import FastAPI, HTTPException
from pydantic import BaseModel, Field
from sqlalchemy import select

from app.config import settings
from app.db import Base, Contract, SessionDep, engine


@asynccontextmanager
async def lifespan(app: FastAPI):
    Base.metadata.create_all(engine)  # Creates the table if it is missing. Never alters it.
    yield


app = FastAPI(title="Contract drafting", lifespan=lifespan)


@app.get("/health")
def health() -> dict:
    return {"status": "ok", "company": settings.company_name}


def found[T](row: T | None) -> T:
    if row is None:
        raise HTTPException(404, "Not found")
    return row


# Admin API. Not published: the browser reaches it only through Next.js, which asks for
# the admin password.
class Upload(BaseModel):
    notes: str = Field(min_length=20, max_length=50_000)


@app.post("/api/contracts")
def upload(upload: Upload, session: SessionDep) -> dict:
    title = upload.notes.strip().splitlines()[0].strip("# ")[:120]
    contract = Contract(title=title, notes=upload.notes)
    session.add(contract)
    session.commit()
    return {"id": contract.id}


@app.get("/api/contracts")
def list_contracts(session: SessionDep) -> list[dict]:
    columns = Contract.id, Contract.title, Contract.status, Contract.contract_type
    return session.execute(select(*columns).order_by(Contract.id.desc())).mappings().all()


@app.get("/api/contracts/{contract_id}")
def get_contract(contract_id: int, session: SessionDep) -> dict:
    return found(session.get(Contract, contract_id)).as_dict()

Upload rejects notes under 20 or over 50,000 characters with a 422 before your code runs. The first line of the notes becomes the title for now.

upload creates a Contract, adds it to the session, and commits. After the commit the object has its id from Postgres. The list selects only the four columns the admin page shows. found() turns a missing row into a 404, for a contract here and for any other row later.

This API has no login

FastAPI is never published. In the admin page the browser reaches it only through Next.js, which asks for the password.

Check

With the API still running, open a second terminal in the project root.

curl -H 'content-type: application/json' \
  -d '{"notes": "# Test client\nWe agreed on a fixed price of $9,000."}' \
  http://localhost:8000/api/contracts
# {"id":1}

curl http://localhost:8000/api/contracts
# [{"id":1,"title":"Test client","status":"pending","contract_type":null}]

curl http://localhost:8000/api/contracts/1

The last call returns the whole contract with status pending. It stays pending for now, because nothing processes it yet.

TestExpected
Upload notes under 20 characters422
Read /api/contracts/999404 with {"detail":"Not found"}
config.py
db.py
main.py
docker-compose.yml

On this page