Skip to content

Typed operations and OpenAPI

A typed operation is a JSON endpoint described as a value: method, path, typed parameters, the body type and its validator, the response type, the permission and the expected failures. The router serves it like any route. The framework writes an OpenAPI 3.1 document from the same values, and the single-page application’s TypeScript client and Zod schemas are generated from that document. One source, three consumers: the server, the document, the browser.

The rules are in the OpenAPI specification, shared by the Java and Go frameworks. The output is deterministic, so the same API gives byte-identical documents from both. Plain routes (GET /health and the like) keep working and are not in the document: receivers, health, metrics, the SPA’s files, login redirects and Datastar streams stay plain routes. See HTTP for those.

Operations are values written once.

public static final PathParam<String> ORDER_ID = PathParam.string("orderId");
public static final QueryParam<@Nullable OrderStatus> STATUS = QueryParam.enumOf("status", OrderStatus.class).optional();
public static final QueryParam<Integer> LIMIT = QueryParam.integer("limit").defaultValue(50);
public static final Operation<NoBody, Page<OrderSummaryView>> LIST =
Operation.get("/api/orders", new TypeRef<Page<OrderSummaryView>>() {})
.id("listOrders")
.summary("List the client's orders")
.tag("orders")
.query(STATUS, LIMIT, AFTER)
.permission(READ)
.build();
public static final Operation<AddLineBody, OrderView> ADD_LINE =
Operation.post("/api/orders/{orderId}/lines", AddLineBody.V, OrderView.class)
.id("addOrderLine")
.summary("Add a line to an open order")
.tag("orders")
.path(ORDER_ID)
.permission(MANAGE)
.error(404, "ORDER_NOT_FOUND", "there is no such order")
.error(409, "ORDER_NOT_OPEN", "the order is cancelled and cannot change")
.build();
Part What to know
factories Operation.get and delete take the response. post, put and patch take the body’s Validator and the response. Operation.post(pattern, Response.class) is a body-less POST. A generic response goes through new TypeRef<Page<X>>() {}
id Required, [a-z][A-Za-z0-9]*, unique. It becomes the TypeScript function name
path(...) Every {name} of the pattern needs a PathParam: string, integer, longInt, enumOf(name, Enum.class)
query(...) QueryParam.string, integer, longInt, bool, enumOf. Required unless .optional() (reads null when absent), .defaultValue(v) or .list() (repeated, empty when absent)
status 200 by default, 201 or 202. A NoBody response is always 204
requiresContext(), permission(p) The operation needs a Context. permission implies it and answers 403 FORBIDDEN when Context.hasPermission(p) is false
error(status, code, message) An expected failure, listed in the document. Repeatable

build() never throws for a mistake in the descriptor. operation.problems() lists them, and they fail start-up and the openapi command with every problem named, so a static final never breaks class loading.

Declare at declaration time, bind at build time

Section titled “Declare at declaration time, bind at build time”

Declaring is what lets the document be written with no configuration and no database. Binding needs the services, so it happens later.

Declare in register, bind in boot:

@Override
public void register(AppBuilder app) {
OpenApi.declare(app, OrdersApi.LIST, OrdersApi.GET, OrdersApi.PLACE, OrdersApi.ADD_LINE, OrdersApi.CANCEL);
OpenApi.info(app, "orders-demo", "1");
}
routes.bind(OrdersApi.PLACE, r -> {
Context context = r.context();
Outcome<OrderView> out =
then(
useCases.run(orders.placeOrder(), context, new PlaceOrder(r.body().customer())),
placed -> view(repository, db, context, placed.orderId()));
return out instanceof Outcome.Ok<OrderView> ok ? ok.header("Location", "/api/orders/" + ok.value().id()) : out;
});

A use case’s failure passes straight through, because a UseCaseError is a ServiceError:

private static <E extends DomainEvent> Outcome<OrderView> then(UseCaseResult<E> result, Step<E> next) throws Exception {
return switch (result) {
case UseCaseResult.Committed<E> c -> next.apply(c.event());
case UseCaseResult.Failed<E> f -> Outcome.failed(f.error());
};
}

The handler gets an OperationRequest: body() (decoded and validated; NoBody.VALUE for none), path(PARAM), query(PARAM), context() and raw(). It returns an Outcome:

Outcome Answer
Outcome.ok(value) The operation’s status and the value as JSON. .header(name, value) appends a header
Outcome.noContent() 204 for a NoBody operation
Outcome.failed(serviceError), Outcome.failed(status, code, message[, details]) The error envelope with that status

OpenApi.info(app, title, version) is called once per application. routes.bind(op, handler, RouteOptions.none().with(middleware)) adds route middleware such as a rate limit.

Start-up fails for an operation declared but not bound, bound but not declared, bound twice, two operations with one id, or a descriptor problem. Throwing HttpException (Java) still works. A failure whose status the document does not list is answered as given and logged once at WARN.

  1. The context is resolved (401 without one), then the permission (403 FORBIDDEN), before anything about the request is looked at.
  2. Every path and query parameter, with all errors in one 400 VALIDATION (for example "limit": "INVALID: must be an integer", "q": "REQUIRED: is required").
  3. The body: 415 unless application/json, 400 INVALID_JSON for malformed JSON or an unknown property, 400 VALIDATION with every failed field.
  4. The handler.

Responses of typed operations use a writer that differs from plain routes in three ways. A @Nullable (Java) or omitzero (Go) value that is null is left out. BigDecimal is written as a JSON string ("9.990") and read from a string or a number. Durations are ISO-8601 ("PT5M") and instants ISO-8601 UTC. In Java the context ids (ClientId, PrincipalId, ApplicationCode, CorrelationId) are plain strings. Plain routes in Java keep writing null.

The body’s validator is the only source of constraints, and each standard rule describes itself, so the same rules decode, validate and appear in the document.

record PlaceOrderBody(String customer) {
static final Validator<PlaceOrderBody> V =
Validator.of(PlaceOrderBody.class)
.field("customer", PlaceOrderBody::customer, Rules.notBlank(), Rules.maxLength(100));
}

Rule.describe() returns a Constraint and Validator.fields() lists them per field.

All errors are collected, not just the first. The response is 400 VALIDATION with details mapping each field path (lines[1].sku) to "<code>: <message>". How rules become schema constraints:

Rule Schema
notBlank minLength: 1, pattern: "\\S"
minLength, maxLength, range, size minLength, maxLength, minimum/maximum, minItems/maxItems
pattern(regex) ^(?:regex)$
oneOf(values) enum
each(rule), nested the rule on items; the nested validator on the nested type
notNull, custom nothing

A pattern the browser cannot read the same way (inline flags, possessive quantifiers, \A, \z, \p{...}, POSIX classes, named groups) is a problem: use a custom rule, which documents nothing. Two operations whose validators give one type different constraints fail the dump; share the validator or give each its own body type. Where Go rules overlap, the tighter bound wins and an explicit pattern replaces notBlank’s.

The emitter walks the types your operations name, once.

Java Schema
String, boolean, int, long, double (and boxes) string, boolean, integer int32, integer int64, number double
BigDecimal, Instant, LocalDate, Duration, UUID, byte[] string with decimal, date-time, date, duration, uuid, base64
an enum {"type": "string", "enum": [...]} in declaration order
a record a component ($ref), additionalProperties: false
List, Collection, Set array (uniqueItems for a set)
Map<String, V> object with additionalProperties
JsonNode {} (anything)
a sealed interface with @JsonTypeInfo and @JsonSubTypes a oneOf component with a discriminator
a value type you register your schema
  • Required unless @Nullable. @Nullable means “may be absent”, never “may be null”: the property is not required and its schema is not nullable (TypeScript x?: T).
  • Names. A component is named after the type. A record nested in a record or interface is prefixed by it (IngestionView.Route is IngestionViewRoute), a holder class adds nothing, and a generic record is followed by its arguments (Page<OrderSummaryView> is PageOrderSummaryView). Two types with one name fail the dump: rename one or call OpenApi.name(app, Type.class, "OtherName").
  • Sealed interfaces need @JsonTypeInfo(use = NAME, include = PROPERTY, property = "kind") and a @JsonSubTypes naming exactly the permitted records. Each variant becomes <Interface><Variant> with the discriminator as its first property.
  • A value type of your own (such as a money type) needs OpenApi.schema(app, Money.class, Schema.string().pattern(...)). OpenApi.property(app, Record.class, "component", schema) replaces one property’s schema.
  • Refused, naming the path from the operation: Optional, Object, raw and wildcard generics, a Map with a non-String key, arrays other than byte[], float, plain classes, local records, @Nullable inside a type argument, and a top-level response that is a list, a map or a primitive.
  • Jackson annotations. Only @JsonTypeInfo and @JsonSubTypes on sealed interfaces and @JsonIgnore on methods that are not components are understood. Any other fails the dump, as does a public getX() or isX() method on a record without @JsonIgnore. Give the API its own view records rather than exposing an aggregate.

Every operation lists default and, by its shape: 400 with a body or any parameter, 401 and 403 with a context, 413 and 415 with a body, plus each declared error. All of them point at one shared Error component, the error envelope.

The module that resolves the context contributes the security schemes. The auth module adds session (the __Host-fw_session cookie), bearer when bearer tokens are accepted, and dpop (HTTP scheme DPoP) when field workers are enabled; see field workers. An application with its own resolver declares its own scheme (Java: OpenApi.securityScheme(app, "basic", SecurityScheme.httpBasic()); Go: Declared.Security). Operations that need a context list every scheme; public ones list none. A context operation with no scheme fails the dump.

The auth module also declares its two endpoints as operations, getAuthSession (GET /auth/session) and logout (POST /auth/logout), so they are in every document of an application that uses it; see sessions and login. An application that has no auth module can bind them to a 501 NOT_IMPLEMENTED answer with sessionapi.Unavailable(rt) in Go, so the document stays complete.

The HTTP module claims the openapi command. It runs after declaration only: no configuration file, no environment, no database, nothing listens.

java -jar app.jar openapi # to standard output
java -jar app.jar openapi --out web/openapi.json # to the file

Your main passes the arguments to launch. Tools and tests get the same without the command: OpenApi.document(builder.declarations()) returns OpenApiDocument.Written(json) or Refused(problems).

Every problem is printed, one per line, with exit code 1. The output is deterministic: sorted paths and components, fixed key order, formatted like JSON.stringify(doc, null, 2).

The HTTP module also builds the document when it starts, before it opens the port, so a type the document cannot describe fails start-up with every problem named, not only the openapi command (Go reports it as a *fw.StartupError with key openapi). Two problems are left to the command and the tests, because they concern the document rather than a type: a missing info, and an operation that requires a context when no security scheme was contributed. An application that declares no operation is not checked.

To fail a unit test on any problem the command would print, with no committed file:

OpenApiTesting.assertBuilds(OpenApiFixture.app(a -> OpenApiFixture.register(a, OpenApiFixture.ALL)));

Commit the document (web/openapi.json) and let a test fail the build when it is stale. The generated client is then checked against the same file; see the UI package.

OpenApiTesting.assertCommitted(OrdersWeb.builder(), DOCUMENT);

It regenerates the document from the builder’s modules and fails with a line diff when the file differs. Run the test with -Dopenapi.update=true to rewrite the file, then review the diff and commit.

The SPA generates its client from the committed file with @hey-api/openapi-ts. const becomes a literal type and z.literal, a sealed interface or union becomes a discriminated union, and “may be absent” becomes x?: T. Two things to know: hey-api’s bundled fetch runtime does not compile under exactOptionalPropertyTypes (the UI package gives it its own project without that flag), and its Zod plugin turns int64 into z.coerce.bigint() while the TypeScript type is number.

No YAML output, no servers entry, and no request or response validation against the document at run time (by design: the validators on the server are the source).