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.
Declaring operations
Section titled “Declaring operations”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.
ListOrdersOp = httpfw.Get[Page[OrderSummaryView]]("/api/orders"). ID("listOrders").Summary("List the client's orders").Tag("orders"). Query(status, limit, after).Permission(Read).Build()
PlaceOrderOp = httpfw.Post[PlaceOrderBody, OrderView]("/api/orders", placeOrderRules). ID("placeOrder").Summary("Place an order").Tag("orders"). Status(http.StatusCreated).Permission(Manage).Build()Get, Delete and PostNoBody take the response type. Post, Put and Patch take the body type, its
validator and the response type. A response of httpfw.NoBody is 204.
- The id is
[a-z][A-Za-z0-9]*and unique (it becomes the TypeScript function name). Tags are[a-z][a-z0-9-]*. Statusis 200, 201, 202 or 204.Error(status, code, message)documents an expected failure.RequiresContext()resolves thefw.Contextand documents the security schemes and the 401 and 403.Permission(p)implies it, is enforced (403 FORBIDDEN) before anything about the request is read, and is written into the document asx-fw-permission.Buildnever panics. A mistake (a path parameter missing from the pattern, a 204 with a body type) is listed with the operation and reported as a start-up problem and by theopenapicommand.
Parameters are typed values: httpfw.Path[int64]("id"), httpfw.Query[OrderStatus]("status"), then
.Optional(), .Default(v) or .List(). The type is a string, int32, int64, bool or a string type with
EnumValues(). The handler reads them with status.Value(in.Params). A missing or malformed parameter is one
400 VALIDATION naming every bad one (REQUIRED, INVALID).
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:
@Overridepublic 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.
func DeclareAPI(web *httpfw.Declared) { web.Info("orders-demo", "1") web.Operations(ListOrdersOp, GetOrderOp, PlaceOrderOp, AddOrderLineOp, CancelOrderOp)}rt.Bind(httpfw.Handle(ListOrdersOp, a.list))A handler is func(ctx context.Context, cx fw.Context, in httpfw.In[Body]) (Resp, error). in.Body is decoded
and validated, in.Params holds the parsed parameters, in.Request is the request, and in.Header collects
headers for the success response (Location, two Set-Cookies). A returned ServiceError is answered with its
envelope (a *usecase.Error passes straight through).
An optional value is a pointer field with omitzero, and a nil one is left out of the JSON. The emitter refuses a
pointer field without it, so the document and the wire agree.
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.
What a request goes through
Section titled “What a request goes through”- The context is resolved (
401without one), then the permission (403 FORBIDDEN), before anything about the request is looked at. - Every path and query parameter, with all errors in one
400 VALIDATION(for example"limit": "INVALID: must be an integer","q": "REQUIRED: is required"). - The body:
415unlessapplication/json,400 INVALID_JSONfor malformed JSON or an unknown property,400 VALIDATIONwith every failed field. - The handler.
How responses are written
Section titled “How responses are written”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.
Validation as data
Section titled “Validation as data”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.
httpfw/validate:
placeOrderRules = validate.Of( validate.Field("customer", func(b PlaceOrderBody) string { return b.Customer }, validate.NotBlank(), validate.MaxLength(200)))addLineRules = validate.Of( validate.Field("sku", func(b AddLineBody) string { return b.SKU }, validate.NotBlank(), validate.MaxLength(64), validate.Pattern("[A-Z0-9][A-Z0-9-]*")), validate.Field("quantity", func(b AddLineBody) int32 { return b.Quantity }, validate.Range[int32](1, 10_000)))The rules are NotBlank, NotNull, MinLength, MaxLength, Pattern (whole string), Range, Size, OneOf,
Each, Nested, Custom (documents nothing) and Ptr (a nil pointer passes). A body field of an enum type (a
string type with EnumValues()) accepts only the declared values without any rule; anything else is 400 VALIDATION with INVALID_JSON: wrong type or format at the member’s path. OneOf is then only for narrowing
the set.
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.
Schemas from your types
Section titled “Schemas from your types”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.@Nullablemeans “may be absent”, never “may be null”: the property is not required and its schema is not nullable (TypeScriptx?: T). - Names. A component is named after the type. A record nested in a record or interface is prefixed by it
(
IngestionView.RouteisIngestionViewRoute), a holder class adds nothing, and a generic record is followed by its arguments (Page<OrderSummaryView>isPageOrderSummaryView). Two types with one name fail the dump: rename one or callOpenApi.name(app, Type.class, "OtherName"). - Sealed interfaces need
@JsonTypeInfo(use = NAME, include = PROPERTY, property = "kind")and a@JsonSubTypesnaming 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, aMapwith a non-Stringkey, arrays other thanbyte[],float, plain classes, local records,@Nullableinside a type argument, and a top-level response that is a list, a map or a primitive. - Jackson annotations. Only
@JsonTypeInfoand@JsonSubTypeson sealed interfaces and@JsonIgnoreon methods that are not components are understood. Any other fails the dump, as does a publicgetX()orisX()method on a record without@JsonIgnore. Give the API its own view records rather than exposing an aggregate.
| Go | Schema |
|---|---|
string, bool, int32, int64, float64 |
the contract’s table rows |
time.Time |
date-time |
[]byte |
base64 string |
jsontext.Value |
any JSON |
slices, map[string]V |
array, object with additionalProperties |
| a struct | one component named after its type (Page[OrderSummaryView] is PageOrderSummaryView) with additionalProperties: false. A field is required unless it is a pointer or omitzero/omitempty |
a string type with EnumValues() []string |
an enum |
a type with JSONSchema() openapi.Schema |
its own schema |
a slice type with UniqueItems() |
a set |
int, unsigned integers, float32, arrays, maps with other keys, pointer elements, embedded structs, unknown
json options and types that write their own JSON are refused with the path from the operation. Registrations
(Declared.Schema, Name, Property) cover the rest, including openapi.Union (a discriminated union over
struct variants) and openapi.OneOf.
Errors, statuses and security
Section titled “Errors, statuses and security”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.
Writing the document
Section titled “Writing the document”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 outputjava -jar app.jar openapi --out web/openapi.json # to the fileYour 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).
orders-demo openapi # the document on standard outputorders-demo openapi --out web/openapi.jsonThis is a declaration-phase command: Launch runs it right after the Declare functions and never calls the
build function. Any other argument prints the usage and exits 2.
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).
Checked at start-up
Section titled “Checked at start-up”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)));fwtest.OpenAPI(t, web) builds the document as the command does, both checks included, fails the test listing
every problem, and returns the document for a drift check.
Keeping it current
Section titled “Keeping it current”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 orders demo commits web/openapi.json and a test fails when it is stale, using the document returned by
fwtest.OpenAPI.
The generated TypeScript client
Section titled “The generated TypeScript client”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.
Not provided
Section titled “Not provided”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).