<a id="routes-contracts-clients"></a>

# Routes, Contracts & Clients

In Dads, every HTTP endpoint is declared as structured data: path template, access rule, optional rate limit, Zod input schemas, and Zod response schema. The same declaration validates requests at runtime, enforces response shape, generates OpenAPI 3.1, and keeps clients in sync.

![Dads HTTP request lifecycle](https://dadsframework.dev/docs/source/website/site/assets/diagrams/request-lifecycle.svg)

<a id="1-own-wire-shapes-in-contractwirets"></a>

## 1\. Own wire shapes in `contract/wire.ts`

Keep wire contracts independent of database tables and authorization rules. Use `z.strictObject` for untrusted inputs when unknown fields must be rejected at ingress, and explicit `z.object` for responses so internal database columns never leak (`domains/notes/contract/wire.ts`):

```ts
import { z } from "zod";

export const noteInput = z.object({ text: z.string().trim().min(1).max(2000) });
export const note = noteInput.extend({
  id: z.uuid(),
  tenantId: z.uuid(),
});

export const notesExport = "notes.export";

export const noteFeatures = z.object({
  features: z.array(z.string()),
  stateHash: z.string(),
});
```

`domains/<feature>/contract/` contains zero server or database imports, so browser code, mobile SDK generators, and Node.js clients can import it safely.

<a id="2-declare-routes-with-typed-verb-helpers"></a>

## 2\. Declare routes with typed verb helpers

Group your domain's routes with `routeGroup` and verb helpers (`getRoute`, `listRoute`, `postRoute`, `patchRoute`, `deleteRoute`) from `@dads-framework/http` (`domains/notes/server/routes.ts`):

```ts
export function notesRoutes({
  db,
  flags,
  writeWithPermission,
}: Pick<StarterServices, "db" | "flags" | "writeWithPermission">) {
  const notesStore = createNotesStore(db);

  return routeGroup("Notes", [
    getRoute({
      route: { method: "GET", template: "/tenants/:tenantId/notes/features" },
      summary: "Read feature availability for a tenant",
      access: notesAccess,
      params: inTenant,
      response: noteFeatures,
      handler: ({ params }) =>
        flags.execute({ kind: "tenant", tenantId: params.tenantId }),
    }),
    listRoute({
      route: { method: "GET", template: "/tenants/:tenantId/notes" },
      summary: "Read notes in a tenant",
      access: notesAccess,
      params: inTenant,
      item: note,
      query: paginationQuerySchema,
      handler: ({ params, query }) =>
        notesStore.listNotes({
          tenantId: params.tenantId,
          page: query.page,
          perPage: query.perPage,
        }),
    }),
    postRoute({
      route: { method: "POST", template: "/tenants/:tenantId/notes" },
      summary: "Create a note in a tenant",
      access: notesAccess,
      params: inTenant,
      body: noteInput,
      response: note,
      handler: ({ body, params, subject }) => {
        const value = {
          id: randomUUID(),
          tenantId: params.tenantId,
          text: body.text,
        };
        return writeWithPermission(
          { subject, permission: notesPermission, resourceId: params.tenantId },
          (tx) => notesStore.insertNote(tx, value),
        );
      },
    }),
  ]);
}
```

<a id="route-rules-enforced-by-typescript"></a>

### Route rules enforced by TypeScript

*   **Required `access`:** Every route must pass a `PermissionAccess` (via `requires(...)`), `requiresVisible(...)`, `requiresScoped(...)`, `requireSession`, or `publicAccess`. Omitting `access` fails type-checking.
*   **Named capabilities instead of anonymous middleware:** `rateLimit`, timeouts, and serving modes are declared fields on the route or group, never hidden middleware chains.
*   **Response drift protection:** Handler return values are validated against `response` (or `item` on `listRoute`) before leaving the server.

<a id="3-keep-sql-and-drizzle-inside-a-store-module"></a>

## 3\. Keep SQL and Drizzle inside a store module

Keep route handlers thin by placing Drizzle queries in a sibling `server/<feature>-store.ts` module (`domains/notes/server/notes-store.ts`). Route files wire HTTP contracts and access checks; store modules accept `db` or a write transaction `tx` and own SQL queries.

<a id="4-call-routes-with-a-typed-client"></a>

## 4\. Call routes with a typed client

Bind route templates once with `defineRoute` from `@dads-framework/contract` and send validated requests with [`@dads-framework/client-request-transport`](https://dadsframework.dev/docs/package-client-request-transport) (`domains/notes/web-client/index.ts`):

```ts
const collectionPath = "/tenants/:tenantId/notes";
function tenantNotes(tenantId: string) {
  return `/tenants/${encodeURIComponent(tenantId)}/notes`;
}
const list = defineRoute("GET", collectionPath, tenantNotes);
const create = defineRoute("POST", collectionPath, tenantNotes);
const features = defineRoute(
  "GET",
  "/tenants/:tenantId/notes/features",
  (tenantId: string) => `${tenantNotes(tenantId)}/features`,
);

export function listNotes(tenantId: string, page: number, signal: AbortSignal) {
  return getPageFromApi({
    route: list.bind(tenantId),
    returns: note,
    query: { schema: paginationQuerySchema, value: { page, perPage: 12 } },
    signal,
  });
}

export function readFeatures(tenantId: string, signal: AbortSignal) {
  return getFromApi({
    route: features.bind(tenantId),
    returns: noteFeatures,
    signal,
  });
}

export function createNote(tenantId: string, text: string) {
  return sendToApi({
    route: create.bind(tenantId),
    body: { schema: noteInput, value: { text } },
    returns: note,
  });
}
```

`getFromApi`, `getPageFromApi`, and `sendToApi` validate outgoing bodies and parse incoming responses against your Zod schemas, and work in React, Next.js, Vue, Svelte, or Node.js.

<a id="5-generate-openapi-31"></a>

## 5\. Generate OpenAPI 3.1

Pass your composed routes to `buildOpenApiDocument` from `@dads-framework/http` to generate an OpenAPI 3.1 document from the exact same Zod schemas and route metadata.

<a id="next-steps"></a>

## Next steps

*   [Multi-API Composition & CI Gates](https://dadsframework.dev/docs/boundaries-and-apis) to mount domain plugins on separate customer and staff APIs
*   [`@dads-framework/http`](https://dadsframework.dev/docs/package-http) for raw routes, streaming responses, and error types

Canonical page: <https://dadsframework.dev/docs/routes-and-contracts>
