Skip to content
Skills Library
Programming · Building & coding

api-transports

/api-transports

Declare a REST route, a tRPC procedure or an SSE/subscription stream on a module: defineRestRouter, defineTrpcRouter, defineTrpcContract, .withInput/.withOutput/.withPermission/.withDocs, /api/<x> paths (/v1 optional), framework-owned validation (malformed_request 400 vs validation_error 422), throwing a HandledError, why a handler returns a plain value, invalidatedBy read hints and fromProjection cursor reads. Use when someone says 'add a route', 'add an endpoint', 'add a procedure', 'new tRPC query', 'REST handler', 'OpenAPI docs for a route', 'withDocs', 'upgrade_in_progress', 'validate the

Repository
langwatch ↗
Licence
Apache-2.0
Last repository change
27.10.2026

Assessment and security

100/ 100Class: good
Format25 / 25
Frontmatter with name and description, valid name, description up to 1,024 characters, name matching the folder.
Discoverability25 / 25
Description explains when to use the skill, has a reasonable length and uses third person.
Content35 / 35
At least 150 words and at most 500 lines, headings, step lists, examples or code.
Hygiene15 / 15
No placeholders such as TODO, no Windows paths, with a licence.
Riskno signals detected in the scan
Files in this package
1
Scripts
0
HTML comments
0
URLs in SKILL.md
0
Deprecation

No signals detected. Repository changed on 27.10.2026, without references to retired models or APIs.

Licence

Apache-2.0, otwarta: można używać i zmieniać, z zachowaniem licencji i informacji o zmianach.

What it does and when to use it

Declare a REST route, a tRPC procedure or an SSE/subscription stream on a module: defineRestRouter, defineTrpcRouter, defineTrpcContract, .withInput/.withOutput/.withPermission/.withDocs, /api/<x> paths (/v1 optional), framework-owned validation (malformed_request 400 vs validation_error 422), throwing a HandledError, why a handler returns a plain value, invalidatedBy read hints and fromProjection cursor reads. Use when someone says 'add a route', 'add an endpoint', 'add a procedure', 'new tRPC query', 'REST handler', 'OpenAPI docs for a route', 'withDocs', 'upgrade_in_progress', 'validate the

Triggers from the description

add a routeadd an endpointadd a procedurenew tRPC queryREST handlerOpenAPI docs for a routewithDocsupgrade_in_progress
Original author description

Declare a REST route, a tRPC procedure or an SSE/subscription stream on a module: defineRestRouter, defineTrpcRouter, defineTrpcContract, .withInput/.withOutput/.withPermission/.withDocs, /api/<x> paths (/v1 optional), framework-owned validation (malformed_request 400 vs validation_error 422), throwing a HandledError, why a handler returns a plain value, invalidatedBy read hints and fromProjection cursor reads. Use when someone says 'add a route', 'add an endpoint', 'add a procedure', 'new tRPC query', 'REST handler', 'OpenAPI docs for a route', 'withDocs', 'upgrade_in_progress', 'validate the

How it works

  1. The rules that matter
  2. Worked example: one contract, one tRPC binding, one REST route
  3. Refusing: throw a HandledError
  4. Streams and read hints
  5. Traps
  6. Tests
Original SKILL.md headings · 206 lines, 1,944 words
SKILL.md preview
---
name: api-transports
description: "Declare a REST route, a tRPC procedure or an SSE/subscription stream on a module: defineRestRouter, defineTrpcRouter, defineTrpcContract, .withInput/.withOutput/.withPermission/.withDocs, /api/<x> paths (/v1 optional), framework-owned validation (malformed_request 400 vs validation_error 422), throwing a HandledError, why a handler returns a plain value, invalidatedBy read hints and fromProjection cursor reads. Use when someone says 'add a route', 'add an endpoint', 'add a procedure', 'new tRPC query', 'REST handler', 'OpenAPI docs for a route', 'withDocs', 'upgrade_in_progress', 'validate the body', 'return a 404', 'streaming endpoint', 'subscription', 'read hint', 'why is my read stale', or opens a *.rest.ts / *.trpc.ts file."
user-invocable: true
---

# API transports: REST, tRPC, streams

Record: `dev/docs/ARCHITECTURE.md` section 8 (transports), section 12 (errors), the read-hint ("The server never
answers `unchanged`") and "Projection cursor reads" paragraphs of section 10. This skill teaches the shape and the traps and does
not restate rulings. Deleted spellings are section 15; target names are section 16.

A transport file **declares**. It never implements. The module's `*Api` operation holds the behaviour.

Writing the contract itself (`*Api`, schemas, error classes) is the `contract` skill. Not here: how the module gets installed, how stores and peers reach it, how `boot()` opens the hosts.
Those are the `process-composition` and `module-dependencies` skills. A module never mounts
anything; the process mounts every installed module's declarations.

## The rules that matter

1. **tRPC is declared twice, once per half.** The contract declares name, kind, input and output with
   `defineTrpcContract("<ns>")`. The process binds a permission and one handler with
   `defineTrpcRouter(<Name>Api, <ns>Trpc)`. The browser derives its client from the contract.
2. **REST is one complete endpoint per route** (`defineRestRouter(<Name>Api)`), with `.withInput` or
   `.withParams`/`.withQuery`, and `.withOutput` (or `.responds({ ... })` for several statuses).
3. **Output schemas are required.** A tRPC member with no `.withOutput` answers nothing and a handler
   that returns data is refused. A REST route declares `.withOutput` or `.responds` (mandatory, record section 8).
4. **A handler receives `{ input, app, actor, scope, signal }`, calls one `*Api` operation, returns a
   plain value or throws.** The route's declarations add typed members: `target` (the scope the door
   authorised, from `.withPermission(perm, { at })`), `session` (from `.withCredential("cli_token", { session })`)
   and `response` (from `.withResponse`); never a raw request or an arbitrary response object. No `c.json`, no `JSON.parse`, no status branches, no error envelope, no
   `RestErrorHandler`. A handler that needs a branch moves into the module as an `*Api` operation.
5. **The framework owns validation.** Never hand-check a body, a content type or a param. Tighten the
   schema. Unparseable input is the 400 `malformed_request`; parsed but failing the schema is the 422
   `validation_error`. A REST request is authenticated before its body is read, so a bad key is 401/403,
   never 422 or 413. A route that reads its raw body names its media type,
   `.withRawBody("text", { mediaType, because })` (a real caller:
   `enterprise/modules/connect/process/src/transport/connect-hosted.rest.ts`); any other `Content-Type`
   is refused after the door with 415 `unsupported_media_type`. Only the `*-legacy` family and the
   collector add `mismatch: "malformed_request"`, keeping main's 400 (record §8, E9, Alex 2026-10-05;
   protocol responses with body limits: `modules/evaluation/process/src/transport/evaluations-legacy.rest.ts`).
6. **Every wire schema imports from the module's own contract.** No schema declared in the transport file.
7. **Docs live on the route.** `.withDocs({ tags, description, errors? })` in the same `*.rest.ts` file.
   Never a `*-openapi.rules.ts`. An extra status or non-JSON body goes through `documentedResponses()`.
   7a. **Every route serves while the installation upgrades; nothing is declared** (NO-HOLDS, Alex
   2026-10-09). A query the Postgres schema is not ready for answers the handled
   `upgrade_in_progress` (503, Retry-After) on REST, tRPC and SSE alike, mapped once in
   `promoteStoreFailure` (`packages/api/src/errors.ts`); never catch it per route (`upgrade` skill).
8. **Paths are `/api/<x>`; `/api/v1/<x>` also answers.** Dated and `latest` versions exist but stay
   hidden (ADR `packages/api/adrs/004-public-rest-v1-and-date-negotiation.md`). A path parameter is named
   for what it identifies (`:triggerId`, never `:id`), except a route main already publishes.
   **A path in another module's namespace is declared, never borrowed** (record §8, R10, Alex
   2026-10-06). When a door moves owner with its path unchanged, the new owner serves it from a
   literal family and declares `.withSharedPath({ owner: "project", reason, deprecate })`: the module
   whose namespace it is, why, and the plan or release that retires it. A blank reason or plan is
   refused, a family claiming `/api/<x>` may not carry one, and a second module claiming a namespace is
   refused at mount. The route registry lists every shared path (`packages/api/specs/shared-path.feature`).
   A dated family (`/<version>/...`) may carry one too when every route in it shares one owner's namespace.
   `withSharedPath` takes `permanent: true` instead of `deprecate` only for a ruled-permanent
   path; the owner must be the namespace's owner in modules/catalogue.json `restNamespaces`.
9. **Auth is the process's.** REST authenticates with API keys, tRPC with the session. A route names a
   permission (`.withPermission("triggers:view")`), never a credential source. The caller arrives as
   `actor`/`scope`; no handler reads headers or looks the key's owner up.
   The door asks the permission before the handler runs. Never declare
   `.withAccess(anyAuthenticated(...))` and then ask a permission in a middleware context, the handler or
   the `*Api`: that is a bypass. `{ at: "route", param }` asks at the scope the path names; on the
   `api_key` door `{ at: "grants" }` passes a key naming no project on any scope it is granted at, and
   `{ at: "organization" }` asks at the organization. A credential bound by the module is a typed
   door: `defineRestDoor(credential, { needs, identify })`, bound with `.withDoors({...})` keyed by the
   routes' credentials (a route naming a credential nobody bound refuses the boot; `packages/api/src/rest/door.ts`).
   An endpoint that mints a key, token or secret declares `.mintsCredential(permission)` and is
   refused while the actor carries an impersonator. `optionalCredential({ reason, refused: "anonymous" })`
   answers a credential the door refuses as no caller. If none fits, extend `packages/api` and the
   door (`modules/auth/process/src/services/api-door.service.ts`), with a spec scenario in
   `packages/api/specs/transport-declaration-split.feature`. A service keeps only the check that needs
   the loaded row.
   **Middleware never does the framework's work** (record §8, 2026-10-05): middleware that
   authenticates or parses a JSON body, and a route opened to any authenticated or unauthenticated
   caller, are drift that lint rules catch; the guard list is
   `dev/docs/plans/api-framework-bypass-2026-10-05.md`. The extensions that plan lists have landed as
   typed doors, credential minting and typed middleware context (record §8); a new framework
   extension is still shaped first: Alex approves the signature and one example route before it is built.
   **The audit is declared too.** A mutation whose row names the organization holding the project its
   input names declares `.withAudit({ target: "organization", via: "projectId" })` (record §8, E10,
   Alex 2026-10-05; `modules/instant-eval/process/src/transport/instant-eval.trpc.ts`). The door resolves
   the organization; never write an audit row by hand.
10. **A query never returns a credential.** Secrets come back only from a mutation.
11. **What a route needs beyond its input is middleware context its own module provides** (record §8,
    Alex 2026-10-10). Declare it `defineMiddlewareContext("name", schema)`, name it on the route with
    `.withMiddlewareContext(name)` (the handler gets the parsed value after its arguments), and supply
    every one in the module installer: `.provideMiddlewareContext({ name: (request, { app, dependencies })
   => value })`. A missing key, an extra key or a value of the wrong type does not compile, and a module
    whose routes need context it never provides does not publish. No process supplies it: a value several
    modules need is a shared helper (`projectRequestContext: projectRequestContextOf`). `.withHeaders(...)`
    values bind themselves. A tRPC procedure uses the same `.withMiddlewareContext(x)`; its mount binds it
    with `bindTrpcMiddlewareContext(x, (ctx) => value)` or `bindTrpcHeader`. Anything else a module binds by
    hand (tRPC, websocket, the API door) goes in `.provideMiddlewareBindings(() => [...])`, type-checked the
    same way. Need the browser session the door resolved? `.withMiddlewareContext(browserSessionContext)`,
    provided by `browserSession: browserSessionOfRequest`; never verify the cookie again.

## Worked example: one contract, one tRPC binding, one REST route

Contract (`modules/automation/contract/src/automation.trpc.ts`):

```ts
export const automationTrpc = defineTrpcContract("automation")
  .mutation("deleteById")
  .withInput(automationApiTriggerScopeSchema)
  .withOutput(automationDeletedSchema)

  .query("getTriggers")
  .withInput(automationApiProjectScopeSchema)
  .withOutput(automationListRowSchema.array());
```

Process (`modules/automation/process/src/transport/automation.trpc.ts`): permission plus one call.

```ts
defineTrpcRouter(AutomationApi, automationTrpc)
  .procedure("getTriggers")
  .withPermission("triggers:view")
  .handle(({ app, input }) => app.listAutomations({ projectId: input.projectId }));
```

REST (`.../transport/automation.rest.ts`, abridged): a namespace, a version, then complete routes. The
route reads `projectRequestContext`, middleware context the module's installer provides
(rule 11), as the handler's second argument; `automationWire` is that file's mapper.

```ts
defineRestRouter(AutomationApi)
  .withNamespace("triggers")
  .withVersion(MANAGEMENT_API_VERSION)
  .get("/:triggerId", "getApiTriggersById")
  .withParams(automationRestIdParamsSchema)
  .withPermission("triggers:view")
  .responds({ 200: automationRestResponseSchema, 404: badRequestSchema })
  .withDocs({ tags: ["Triggers"], description: "Get a trigger by its ID" })
  .withMiddlewareContext(projectRequestContext)
  .handle(async ({ app, input, scope }, project) => {
    const trigger = await app.getPublicTrigger({ triggerId: input.triggerId, projectId: scope.id });
    return {
      status: 200 as const,
      body: automationWire({ app, projectSlug: project.projectSlug, trigger }),
    };
  });
```

A POST that creates declares `.withInput(...)`, `.withStatus(201)` and `.withOutput(...)` in the same
way (`.post("/", "postApiTriggers")` in that file). A bodiless action declares an empty input schema from
its contract (`automationRestNoBodySchema`, record section 8).

## Refusing: throw a HandledError

Throw `HandledError` only when the cause is known and the caller can act on it. The class lives in
the module's contract (`modules/automation/contract/src/automation.errors.ts`: `TriggerNotFoundError`
carries `code: "trigger_not_found"` and `httpStatus: 404`). The service throws it; the transport lets it
escape. The REST runtime renders `type`, `code`, `message` at the root of the body, and tRPC sends the
code slug. Register the code in `packages/handled-error/src/app-codes.ts`, its customer copy in
`presentation.ts` and its tips in `remediation.ts` (the `contract` skill has the recipe). Never a `TRPCError`. Never set `Retry-After` yourself:
`meta.retryAfterMs` renders it. Everything unknown stays a plain `Error`; the boundary degrades it to
"unknown" plus a trace id. Detail: `dev/docs/best_practices/error-handling.md`.

## Streams and read hints

- A **stream** is a tRPC `.subscription(name)` in the contract; its `.withOutput` describes ONE yielded
  value. The process binds it like a procedure (`modules/presence/process/src/transport/presence.trpc.ts`,
  `onOrganizationReadHints`, which gets `signal` to stop). The API host serves it on `/api/sse/*`.
- A non-tRPC SSE route declares `.withResponse("sse", ...)` (covered by
  `packages/api/src/rest/__tests__/response-kind.integration.test.ts`). A protocol that must write the
  raw response itself is a declared raw HTTP door (record section 8), never a handler hack.
- **Reads answer in full.** The server never answers `unchanged` and never sends an ETag or a 304.
  The browser caches and decides when to refetch.
- **Say when a read goes stale** on its contract, not in the screen:
  `.query("getScopeGraph", { invalidatedBy: ["lw.project.created"] })`, or with a scope field
  `{ event, scope: "organizationId" }`. The framework hints on each committed event; the browser refetches.
  Hints carry no data. No timer polling.
- **Projection-backed reads** declare `{ fromProjection: ["<projection>"] }` instead (never both). The
  cursor is the event id; see `eventing-and-worker` and the "Projection cursor reads" paragraph.
- Every read is mirrored to the browser's disk by default (§10); there is no opt-in and `cache: { persist }`
  is a deleted spelling (§15). High-traffic reads go on `UI_QUERY_MIRROR_EXCLUDED`
  (`@langwatch/browser-host/cache-tiers`). `revision: n` is bumped only when a read's meaning changes
  and its shape does not.
- Specs: `packages/api/specs/read-hints.feature`, `packages/eventing/specs/projection-cursor-reads.feature`.

## Traps

| Trap                                                                      | Instead                                                           |
| ------------------------------------------------------------------------- | ----------------------------------------------------------------- |
| `c.json(...)`, `try/catch` into a status                                  | return the value; throw a HandledError                            |
| checking `typeof body.x` in a handler                                     | tighten the Zod schema in the contract                            |
| `:id` on a new route                                                      | `:<thing>Id`                                                      |
| a docs object in `*-openapi.rules.ts` (deleted, §15)                      | `.withDocs()` on the route                                        |
| a handler calling two `*Api` operations                                   | one operation that carries both                                   |
| a new procedure name chosen casually                                      | the wire name is the browser's cache key; choose once             |
| a secret in a query output                                                | a mutation returns it once; forms read blank                      |
| a raw `/api/cron/*` route                                                 | a scheduled process manager (`eventing-and-worker`)               |
| REST route for the UI                                                     | the UI uses tRPC; REST is key-authenticated public API            |
| a route escaping access without a reason (`langwatch/access-escape-kind`) | `.withPermission(...)`, or pass `{ reason }` to the escape        |
| reading the auth header in a handler (`langwatch/auth-header-read`)       | take `actor` and `scope` from the handler the door resolved       |
| a hand-rolled credential reader (`langwatch/credential-reader-owner`)     | declare `.withPermission(...)` or `.withAccess(...)` on the route |
| reading the raw body (`langwatch/raw-body-bypass`)                        | `.withInput(schema)`; `.withRawBody` needs `{ because }`          |

## Tests

Mount the real router on a real runtime and assert status, body and `code`:
`modules/automation/process/src/transport/__tests__/automation.rest.integration.test.ts` and
`automation.trpc.unit.test.ts`. See the `testing` skill. A changed route, name, status or permission is a
wire change: diff the served surface against `origin/main` and record every difference. After adding
or changing a route, procedure or socket, run `pnpm generate:readmes`: the module's `process/README.md`
is the review artefact (`readmes` skill).

Versions

The database has no other skills named api-transports.

Database snapshot: 13.11.2026 · package version 6607a71cccc7 (SHA-256 digest of the entire package)

Downloads in the last 30 days: 2 · ranking

Report a problem with this skill: harmful content, incorrect descriptions or an author’s removal request.

Similar skills

  • 100contract
    Write or change a module's contract package (modules/<name>/contract): the `*Api` interface and moduleApi token, Zod schemas with z.infer, HandledError subclasses and their codes, the tRPC declarations (defineTrpcContract), REST wire schemas, method verbs (get/find/list,…
  • 100trpc
    tRPC for type-safe APIs. Covers routers, procedures, and React Query integration. Use for end-to-end type-safe APIs. USE WHEN: user mentions "tRPC", "type-safe API", "end-to-end types", "procedures", "tRPC router", "tRPC React Query", asks about "how to build type-safe API",…
  • 95trpc
    tRPC v11 end-to-end type-safe APIs with Next.js App Router — routers, procedures, middleware, subscriptions, React Query integration. Use when building type-safe APIs without REST/GraphQL, or when maximum type safety between client and server is needed.
  • 90api-patterns
    API design decisions - REST vs GraphQL vs tRPC, responses, versioning, auth, rate limits. Use when designing an API.
  • 90api-patterns
    Chooses REST, GraphQL or tRPC and sets versioning, pagination, auth and rate limits. Use when designing an API or reviewing endpoint contracts.
  • 100factory-api-route-engineer
    Use when designing or implementing API endpoints — server actions, tRPC procedures, REST routes for external consumers. Carries the factory's API conventions — the server actions vs tRPC decision, procedure tier stacking, per-mutation Zod schemas, central router composition with…

Feedback and reports

Your message goes to Bartosz Sokoliński. An email address is needed only for a reply. See the privacy policy.