Skip to content

Chapter 18 — The Booking Desk API#

Act V · Chapter 18 Launch Day · 08:00 7 min readDifficulty 2 of 5

FastAPI request models derived from your tables, and JSON encoded directly from wire bytes in Rust.

pg.Create[T]pg.Patch[T]pool.json()pool.stats().tag()
▶ Run it yourself · examples/117_web_api_and_telemetry.py
Launch Day, 08:00. The lobby doors open in one hour, and the web frontend needs `POST /guests`, `PATCH /guests/{id}`, and `GET /guests-raw`.

Launch Day, 08:00. The lobby doors open in one hour, and the web frontend needs POST /guests, PATCH /guests/{id}, and GET /guests-raw.

Panda: Easy! Copy-paste every Guest column into GuestCreate, GuestPatch, and GuestResponse Pydantic classes! Then fetch every row as a Python object, convert it to a dict, and serialize it to JSON!

Maya: Why write three copies of the same table when pg.Create[Guest] and pg.Patch[Guest] derive themselves — and Ferris can encode /guests-raw from wire bytes straight to JSON in Rust?

The mission#

Glue code between an ORM and a web framework is where subtle drift hides: add a column to your table, forget to add it to GuestPatch, and the API silently ignores it. Maya wires FastAPI directly to pgdorm with zero boilerplate:

  1. derive validated POST and PATCH Pydantic payloads straight from Guest using pg.Create[Guest] and pg.Patch[Guest],
  2. encode read-heavy JSON endpoints directly from PG binary wire tuples in Rust via pool.json() with zero Python object hydration,
  3. observe live query counts and open connections through pool.stats() and .tag(...).

The Panda's plan

Maintain parallel GuestCreate, GuestUpdate, and GuestOut models by hand, manually call .model_dump(exclude_unset=True), and hydrate 5,000 Guest Python objects on GET /guests just to call json.dumps(...) on them one millisecond later.

1. FastAPI endpoints with Create[T], Patch[T] and pool.json()#

First, a tiny response shape for the PATCH route so we can inspect which fields were actually touched:

examples/117_web_api_and_telemetry.py · PatchGuestOut
class PatchGuestOut(BaseModel):
    full_name: str
    phone: str | None
    dirty_fields: list[str]

Now build the three routes — notice Guest itself is both the database table and the FastAPI response model:

examples/117_web_api_and_telemetry.py · build_app
def build_app(pool: pg.Pool) -> FastAPI:
    app = FastAPI(title="The Elephant Dormitory Desk API")

    @app.post("/guests")
    async def create_guest(body: pg.Create[Guest]) -> Guest:
        return await pool.one(
            pg.insert(Guest).values(body).returning(Guest).tag("api.create_guest")
        )

    @app.patch("/guests/{guest_id}")
    async def patch_guest(guest_id: int, body: pg.Patch[Guest]) -> PatchGuestOut:
        updated = await pool.one(
            pg.update(Guest)
            .patch(body)
            .where(Guest.guest_id == guest_id)
            .returning(Guest)
            .tag("api.patch_guest")
        )
        return PatchGuestOut(
            full_name=updated.full_name,
            phone=updated.phone,
            dirty_fields=list(body.dirty_fields()),
        )

    @app.get("/guests-raw")
    async def list_guests_raw() -> Response:
        # Encodes PG binary wire rows straight to UTF-8 JSON bytes in Rust (zero Python hydration).
        payload = await pool.json(
            pg.select(Guest).order_by(Guest.guest_id.asc()).tag("api.list_guests_raw")
        )
        return Response(content=payload, media_type="application/json")

    return app

What just happened

  • body: pg.Create[Guest] generates a Pydantic-validated input schema automatically, excluding server-generated columns (guest_id, public_id, full_name, created_at) while enforcing required fields and types.
  • body: pg.Patch[Guest] generates a partial-update schema that tracks body.dirty_fields() accurately. Passing it to pg.update(Guest).patch(body) emits SQL SET clauses only for the keys that actually arrived in the JSON request body (distinguishing omitted fields from explicit null!).
  • await pool.json(pg.select(Guest)...) executes the normal typed SELECT, reads PostgreSQL's binary wire rows inside Rust, and encodes them directly into ready-to-send UTF-8 JSON bytes for Response(content=payload, media_type="application/json") — skipping Python model hydration and Pydantic serialization altogether.

2. Exercise the API and inspect pool.stats()#

Using httpx.ASGITransport, Maya exercises all three routes in-process and checks live pool telemetry:

examples/117_web_api_and_telemetry.py · exercise_desk_api
async def exercise_desk_api(pool: pg.Pool) -> None:
    app = build_app(pool)
    transport = httpx.ASGITransport(app=app)
    before = pool.stats()

    async with httpx.AsyncClient(transport=transport, base_url="http://dorm") as client:
        # 1. POST Create[Guest] -> validates JSON, skips identity/generated cols, returns Guest.
        r_post = await client.post(
            "/guests",
            json={
                "email": "[email protected]",
                "first_name": "Raja",
                "last_name": "Ngorongoro",
                "species": int(Species.SAVANNA),
                "country": "TZ",
            },
        )
        created = r_post.json()
        print(
            f"POST /guests -> {r_post.status_code} {created['full_name']} "
            f"({created['email']}) badge={created['public_id']}"
        )
        # => POST /guests -> 200 Raja Ngorongoro ([email protected]) badge=<UUIDv7>

        # 2. PATCH Patch[Guest] -> tracks exact dirty fields; omitted cols stay UNSET.
        r_patch = await client.patch(
            f"/guests/{created['guest_id']}",
            json={"phone": "+255 754 000 111"},
        )
        patched = r_patch.json()
        print(f"PATCH /guests -> dirty={patched['dirty_fields']} phone={patched['phone']}")
        # => PATCH /guests -> dirty=['phone'] phone=+255 754 000 111

        # 3. GET /guests-raw -> zero-hydration JSON bytes encoded in Rust from PG binary wire.
        r_raw = await client.get("/guests-raw")
        raw_rows = r_raw.json()
        print(f"GET /guests-raw -> {r_raw.status_code} ({len(raw_rows)} guest in wire JSON)")
        # => GET /guests-raw -> 200 (1 guest in wire JSON)

    after = pool.stats()
    delta_q = after.queries_executed - before.queries_executed
    print(f"pool telemetry: +{delta_q} queries executed, open_conns={after.connections_open}")
    # => pool telemetry: +3 queries executed, open_conns=1

What just happened

  • "[email protected]" passed straight through LowerEmail on insert and returned [email protected] plus the PostgreSQL virtual full_name (Raja Ngorongoro) and UUIDv7 badge.
  • PATCH /guests/{id} with {"phone": "+255 754 000 111"} marked only dirty=['phone'], leaving every other column untouched.
  • GET /guests-raw returned valid UTF-8 JSON encoded in Rust directly from PostgreSQL's binary wire rows without constructing a single Python Guest object.
  • pool.stats() confirmed +3 queries executed, open_conns=1 — and every query carried its /* op:api.* */ comment tag for pg_stat_statements and APM dashboards.
Ferris' basement: zero-hydration JSON vs typed models

Use pool.all(...) / pool.one(...) whenever your Python code needs to inspect fields, run business logic, or branch on types. Use pool.json(...) on read-only passthrough endpoints (like search listings or dashboards) where Python was only going to serialize the rows straight back to JSON anyway — skipping object allocation and Pydantic serialization slashes CPU time and memory pressure.

What PostgreSQL actually received#

🔭 What PostgreSQL received: 3 statements in 3 round trips (captured live on PostgreSQL)
-- ⚙ schema setup (create_all): 19 statements omitted · full transcript in examples/__wire__/web_api_and_telemetry.sql

-- ── round trip 1 ──
INSERT INTO "guest" ("email", "first_name", "last_name", "species", "phone", "country", "birth_date", "loyalty_tier", "peanut_points", "preferences", "marketing_opt_in")
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)
RETURNING "guest_id", "public_id", "email", "first_name", "last_name", "full_name", "species", "phone", "country", "birth_date", "loyalty_tier", "peanut_points", "preferences", "marketing_opt_in", "created_at"
/* op:api.create_guest */;
-- → 1 row

-- ── round trip 2 ──
UPDATE "guest"
SET "phone" = $1
WHERE "guest_id" = $2
RETURNING "guest_id", "public_id", "email", "first_name", "last_name", "full_name", "species", "phone", "country", "birth_date", "loyalty_tier", "peanut_points", "preferences", "marketing_opt_in", "created_at"
/* op:api.patch_guest */;
-- → 1 row

-- ── round trip 3 ──
SELECT
  "guest_id",
  "public_id",
  "email",
  "first_name",
  "last_name",
  "full_name",
  "species",
  "phone",
  "country",
  "birth_date",
  "loyalty_tier",
  "peanut_points",
  "preferences",
  "marketing_opt_in",
  "created_at"
FROM "guest"
ORDER BY "guest_id" ASC
/* op:api.list_guests_raw */;
-- → 1 row

Shift report

  • Derived FastAPI request schemas automatically with pg.Create[T] and pg.Patch[T]
  • Applied dirty-only updates safely with pg.update(T).patch(body)
  • Encoded JSON bytes directly in Rust from PG binary rows with pool.json()
  • Monitored query counts and open connections with pool.stats() and .tag()

Try it yourself

Send a second PATCH in exercise_desk_api with json={"phone": None} and inspect dirty_fields and the updated row. Notice pg.Patch[Guest] distinguishes an explicit null from an omitted key cleanly!

Go deeper: tests/integration/runtime/web/test_web.py · tests/integration/runtime/telemetry/test_telemetry.py (live PostgreSQL test suites & snapshots)

Note

Also in pgdorm: Switch between client wire transcoding (mode="wire") and PostgreSQL-side json_agg (pool.json(q, mode="server") via JsonMode), and plug in custom observability with TelemetryHook + set_telemetry — see the Runtime & Pool Reference.

Sticky note from Management

"NOON RUSH! We need to add rfid_tag (unique) and tusk_span_cm (positive check constraint) to dorm_badge RIGHT NOW — while the lobby is full. Do NOT lock out check-ins!"