OpenAPI schema generation for http4k contract endpoints driven by kotlinx.serialization descriptors rather than Jackson reflection.
http4k's AutoJsonToJsonSchema uses Java/Kotlin reflection to walk object properties. This breaks with kotlinx.serialization where:
@SerialNameannotations are invisible to reflection- Sealed class polymorphism requires manual workarounds (SealedClassSchemaOverride or full forks)
- Nullable fields are not reliably detected from reflected properties
Services using kotlinx.serialization carry 100-250 lines of per-service override code to work around these limitations.
http4k's SchemaNode is a MutableMap<String,Any?> that gets serialized via json.asJsonObject(). It has no support for oneOf/discriminator schema constructs needed for sealed classes.
Decision: Build JSON schema NODE directly via http4k's json DSL (obj/string/array) instead of going through SchemaNode. This gives full control over schema structure without forking http4k internals.
Tradeoff: We bypass SchemaNode entirely. If http4k changes its json DSL API, we need to adapt. However, the json DSL is stable and used widely across http4k.
ApiRenderer.Auto() has an internal fallback chain:
- Try treating the value as NODE (
JsonToJsonSchema) - On
ClassCastException, fall back to schema creator
Our implementation is the schema creator path. This is a supported extension point, not a hack.
kotlinx.serialization's SealedClassSerializer builds descriptors with:
element[0]= discriminator propertyelement[1]= container of all subclass descriptors
Risk: This is an implementation detail, not a stable API.
Mitigation: Defensive validation at runtime:
- Verify
elementsCount >= 2and throw a descriptive error otherwise. element[0].serialNameis deliberately not compared to the discriminator. It is always theSealedClassSerializer's generator default (type), never a per-hierarchy@JsonClassDiscriminatoroverride, so that comparison would reject valid overridden hierarchies. The discriminator name is read from@JsonClassDiscriminatoron the descriptor, falling back toJson.classDiscriminator.
If kotlinx.serialization changes this structure, tests fail immediately with clear error messages.
Schema structure comes from SerialDescriptor traversal. Example values come from serializing the example object to JSON and navigating the resulting JsonObject by field name.
For each descriptor element at index i, look up descriptor.getElementName(i) in the JsonObject to get the field's JSON value.
Why not use descriptor for both?: SerialDescriptor provides structure but not runtime values. The example object contains the values but reflection can't extract them correctly (see @SerialName issue above).
We obtain SerialDescriptor via kotlinxJson.serializersModule.serializer(obj::class.java). Generic type information is erased at this entry point.
Why acceptable: toSchema receives concrete @Serializable wrapper DTOs from http4k contract routes. These are always concrete types, not generic List or Map<K,V> in the abstract. Inside the descriptor walk, generic argument types and inline value-class inner types are recovered by threading a KType through traversal, so collection element types and inline-class wrappers resolve correctly even though the top-level entry point can't see them.
object {} sentinel: http4k calls toSchema(object {}) from exampleSchemaIsValid to probe the comparator path. Resolving a serializer for an anonymous object throws SerializationException; we catch it and return an empty JsonSchema so the comparison succeeds. All other unregistered-serializer cases propagate the exception as-is (fail-fast).
kotlinx.serialization's compiler plugin excludes @Transient fields from both:
SerialDescriptor.elementDescriptorsencodeToJsonElementoutput
Decision: No special handling needed. They're invisible to our code automatically.
OPEN polymorphism has a runtime-dynamic subclass set incompatible with static JSON Schema generation. No known Liflig service uses OPEN for API DTOs.
Decision: Throw IllegalArgumentException immediately if encountered. Better to fail fast than silently generate incomplete schemas.
Liflig services follow a pattern where DTOs expose example instances via companion object example property. SealedClassExampleProvider discovers these via reflection on companionObjectInstance.
The schema creator doesn't care about this pattern - it just receives whatever example instance arrives via toSchema(obj). The example provider is a separate concern.
Short definition names are derived from serialName (e.g., com.example.UserDto -> UserDto). On collision (different serialName, same short name), both the existing and new definitions are re-keyed to full underscore-separated names (com_example_UserDto).
refModelNamePrefix is applied after collision resolution, not before.
Add the dependency to your pom.xml:
<dependency>
<groupId>no.liflig</groupId>
<artifactId>http4k-openapi-kotlinx-serialization</artifactId>
<version>${http4k-openapi-kotlinx-serialization.version}</version>
</dependency>You also need http4k's OpenAPI and kotlinx.serialization dependencies. See the project's pom.xml for the full list.
@Description is most useful on shared vocabulary types — a TrainNumber or a NominalDate described once, rather than at every field holding it. Those types usually live in a domain-types library that has no business depending on http4k.
For that case, depend on the annotations artifact alone. It carries @Description, @AllowedValues and AllowedValuesProvider and nothing else, and pulls in no dependencies beyond kotlin-stdlib:
<dependency>
<groupId>no.liflig</groupId>
<artifactId>http4k-openapi-kotlinx-serialization-annotations</artifactId>
<version>${http4k-openapi-kotlinx-serialization.version}</version>
</dependency>The main artifact depends on it at compile scope, so a service that already has http4k-openapi-kotlinx-serialization needs no second entry — the annotation is on its classpath either way, under the same no.liflig.http4k.kotlinx.jsonschema package. The same holds for @AllowedValues and AllowedValuesProvider.
The openApi3WithKotlinx helper wires everything needed for Jackson-free OpenAPI rendering and defaults to OpenAPI 3.1.0.
By default, nullable fields use type arrays ({"type": ["string", "null"]}) for primitives and plain $ref for reference types. This ensures compatibility with widely used code generators like openapi-generator-cli. See Nullable strategy for details and alternatives.
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonElement
import no.liflig.http4k.kotlinx.jsonschema.KotlinxSerializationJsonSchemaCreator
import no.liflig.http4k.kotlinx.openapi.openApi3WithKotlinx
import org.http4k.contract.contract
import org.http4k.contract.openapi.ApiInfo
import org.http4k.format.KotlinxSerialization
// Pass the same Json instance your service uses elsewhere so the
// serializersModule (contextual serializers, polymorphic registrations) and
// any classDiscriminator override match between runtime encoding and schema
// generation. Settings like ignoreUnknownKeys or prettyPrint do not affect
// schema output.
val kotlinxJson = Json { /* your service's existing config */ }
val schema = KotlinxSerializationJsonSchemaCreator<JsonElement>(
json = KotlinxSerialization,
kotlinxJson = kotlinxJson,
)
val routes = contract {
renderer = openApi3WithKotlinx(
apiInfo = ApiInfo("My API", "1.0.0"),
json = KotlinxSerialization,
schema = schema,
)
routes += "/user" / userId meta {
summary = "Get user"
} bindContract GET to ::getUser
}The helper internally creates a KotlinxOpenApi3Renderer and passes it to http4k's OpenApi3 constructor with version = OpenApiVersion._3_1_0. You can override the version if needed:
openApi3WithKotlinx(
apiInfo = apiInfo,
json = KotlinxSerialization,
schema = schema,
version = OpenApiVersion._3_0_0, // opt in to 3.0 explicitly
)For full control over the OpenApi3 constructor, use KotlinxOpenApi3Renderer directly:
val renderer = KotlinxOpenApi3Renderer(
json = KotlinxSerialization,
schema = schema,
)
val routes = contract {
this.renderer = OpenApi3(
apiInfo = ApiInfo("My API", "1.0.0"),
json = KotlinxSerialization,
apiRenderer = renderer,
version = OpenApiVersion._3_1_0,
)
}Both classes take a refLocationPrefix parameter (default "components/schemas"), the path segment every $ref points under. KotlinxOpenApi3Renderer defaults it from the schema you pass in, so setting it once on KotlinxSerializationJsonSchemaCreator keeps every $ref consistent. Only pass it to KotlinxOpenApi3Renderer explicitly if the two must differ.
Passing apiRenderer as a named parameter forces Kotlin to use the OpenApi3 primary constructor (which takes Json<NODE>). The secondary constructor takes AutoMarshallingJson<NODE> and has no apiRenderer parameter — it always uses ApiRenderer.Auto, which falls back to Jackson and defeats the point of this library.
Array-typed body examples need http4k 6.59.0.0 or newer. OpenApi3 re-parses every body example with Json.parse and silently drops it on failure, and http4k's kotlinx format rejects a top-level JSON array there in older versions, so on those any List<...> request or response body renders without its example.
The renderer's toSchema() first tries JsonToJsonSchema for raw JSON bodies (json.body().toLens() with NODE examples), as ApiRenderer.Auto does, and hands everything else to KotlinxSerializationJsonSchemaCreator. That includes the enum constants http4k passes for query and path parameters, constants with bodies included.
Custom serializers (e.g. for LocalDate, Instant) produce PrimitiveSerialDescriptor with a serialName but no OpenAPI format. The formatMappings parameter lets you map descriptor names to OpenAPI format strings:
val schema = KotlinxSerializationJsonSchemaCreator<JsonElement>(
json = KotlinxSerialization,
kotlinxJson = kotlinxJson,
formatMappings = KotlinxSerializationJsonSchemaCreator.COMMON_FORMAT_MAPPINGS,
)COMMON_FORMAT_MAPPINGS includes:
| Descriptor name | OpenAPI format |
|---|---|
Instant |
date-time |
LocalDate |
date |
LocalDateTime |
date-time |
ZonedDateTime |
date-time |
UUID |
uuid |
URI |
uri |
You can provide your own map or extend the common mappings:
formatMappings = KotlinxSerializationJsonSchemaCreator.COMMON_FORMAT_MAPPINGS + mapOf(
"Duration" to "duration",
)The mapping matches against the short name (after the last .) of the serializer's serialName.
The nullableStrategy parameter controls how nullable fields are represented in the generated JSON Schema. The default (TYPE_ARRAY) is designed for maximum compatibility with code generators.
val schema = KotlinxSerializationJsonSchemaCreator<JsonElement>(
json = KotlinxSerialization,
kotlinxJson = kotlinxJson,
nullableStrategy = NullableStrategy.TYPE_ARRAY, // default
)| Strategy | Nullable primitives | Nullable $ref types |
Best for |
|---|---|---|---|
TYPE_ARRAY (default) |
{"type": ["string", "null"]} |
Plain {"$ref": "..."} (nullability not expressed) |
Code generators (openapi-generator-cli, openapi-typescript, etc.) |
ANYOF |
{"anyOf": [{"type": "string"}, {"type": "null"}]} |
{"anyOf": [{"$ref": "..."}, {"type": "null"}]} |
Strict JSON Schema validators that distinguish "absent" from "null" |
Why TYPE_ARRAY is the default: The anyOf pattern, while semantically precise per OpenAPI 3.1 / JSON Schema 2020-12, was seen to produce empty wrapper interfaces instead of proper nullable types from an earlier, unrecorded version of openapi-generator-cli (the most widely used TypeScript code generator). That does not reproduce with 7.21.0 or newer, which emit T | null. The type array form is equally valid OpenAPI 3.1 and produces correct output from all major generators, old and new.
Trade-off with TYPE_ARRAY: For nullable $ref types (objects, enums, sealed classes), there is no type array to merge "null" into, so the $ref is emitted without a nullable wrapper and the schema says nothing about the field accepting null. If the field also has a Kotlin default it is absent from required, and TypeScript consumers — which treat optional and nullable identically (field?: Type) — end up with the right shape. If it has no default, it is still in required (see Required fields and default values) and the null case is not documented at all.
Limitation — nullable $ref inside collections: at the field level, an optional field at least signals to a generator that the value may be absent. For $ref types inside collection elements — List<Child?>, Map<String, Child?>, Set<Child?> — there is no field-level required at all; the element schema is just a $ref and the rendered schema documents elements that don't accept null. If a DTO uses nullable refs inside collections AND consumers need to distinguish missing from null at the element level, switch to ANYOF.
Limitation — nullable $ref in rendered examples: the renderer keeps null values inside example payloads, because a null there is data — it is what the endpoint actually serializes for a nullable field (kotlinx encodes explicit nulls by default). For a nullable $ref field the example therefore contains "field": null while the schema is a plain $ref that admits only the referenced object, so validators that check examples against their schema (Swagger UI, Spectral, openapi-generator-cli) report a type mismatch on that field. Nullable primitives are unaffected — {"type": ["string", "null"]} accepts the null. Switch to ANYOF if your endpoints return explicit nulls for $ref-typed fields and your tooling validates examples.
Use ANYOF if your schema consumers are strict validators that need to distinguish "field absent" from "field present with value null", if you have nullable refs inside collection elements, or if example payloads containing nulls for $ref fields must validate:
val schema = KotlinxSerializationJsonSchemaCreator<JsonElement>(
json = KotlinxSerialization,
kotlinxJson = kotlinxJson,
nullableStrategy = NullableStrategy.ANYOF,
)A field is added to the OpenAPI required array based on kotlinx.serialization's descriptor.isElementOptional(i), not Kotlin's notion of nullability. The rule:
- No default value → required (regardless of nullability).
- Has a Kotlin default value (e.g.
val x: String = "...") → optional. The compiler plugin marks itisElementOptional = true, so kotlinx can deserialize JSON that omits the field. - Has a default value AND is annotated with
@Required→ required again. Use this when the default is a fallback for in-process construction but the JSON wire format must always include the field.
@Serializable
data class CreateOrderRequest(
val customerId: UUID, // required (no default)
val notes: String? = null, // optional (has default)
@Required val source: String = "web", // required (default + @Required)
)Nullable fields without a default are still required — they just accept null as a value (see Nullable strategy for how that's encoded).
A property annotated with Kotlin's @Deprecated is rendered with "deprecated": true. No configuration is needed, and no extra annotation: the standard kotlin.Deprecated you already use to warn callers in Kotlin is what drives it.
@Serializable
data class JourneyDto(
@Deprecated("Use originPlc instead") val originStop: PrimaryLocationCode,
val originPlc: PrimaryLocationCode,
){
"originStop": { "type": "string", "deprecated": true },
"originPlc": { "type": "string" }
}Properties without the annotation carry no deprecated key at all, rather than "deprecated": false. The marker is placed on the property's outer schema in every shape — alongside type for primitives, as a sibling of $ref for reference types (legal in OpenAPI 3.1 / JSON Schema 2020-12), and outside the branches under NullableStrategy.ANYOF.
Only properties are marked. @Deprecated on a DTO class itself has no effect on the schema.
The marker is rendered; the message is not. "deprecated": true is a fact about the API, so it is derived automatically. The message is prose written for Kotlin callers — "Legacy from the 2019 import, ask before touching" is as plausible as "Use originPlc instead", and it names Kotlin properties rather than serialized field names. Migration guidance a consumer should read goes in @Description, where someone has decided it is consumer-facing:
@Description("The journey's origin. Superseded by originPlc.")
@Deprecated("Use originPlc instead")
val originStop: PrimaryLocationCode@Description renders as "description". It goes on a property, or on a type — a type's description applies to every use of it, which is how a shared vocabulary type gets described once rather than at each field holding it.
@Description("Planned departure date from route origin, per the route plan.")
@Serializable @JvmInline value class NominalDate(val value: LocalDate)
@Serializable
data class TrainIdDto(
@Description("The train number as the traffic systems report it.") val trainNumber: String,
val nominalDate: NominalDate,
){
"trainNumber": { "type": "string", "description": "The train number as the traffic systems report it." },
"nominalDate": { "type": "string", "format": "date", "description": "Planned departure date from route origin, per the route plan." }
}Resolution order for a property: its own @Description, then its type's. Two answers to the same question, so the more specific one wins, and a property with neither carries no description key.
Where a type's description lands depends on how the type renders. A type flattened into the property — an inline value class, or one whose custom serializer produces a primitive — has no definition of its own, so its description goes on each property holding it. A type rendered as $ref does have a definition, and its description goes there, once:
@Description("Which system owns the train at a given time.")
@Serializable enum class ResponsibleSystem { GTS, CONNECT }"components": {
"schemas": {
"ResponsibleSystem": {
"description": "Which system owns the train at a given time.",
"type": "string",
"enum": ["GTS", "CONNECT"]
}
}
}Sealed hierarchies follow the same rule, and both levels are described independently: the base's description lands on the definition holding oneOf and discriminator, and each subclass's on its own definition. A subclass reads the same whether it is reached through its base or referenced directly.
@Description("The lifecycle state of an import.")
@Serializable
sealed class ImportState {
@Description("The import finished without errors.")
@Serializable @SerialName("completed") data class Completed(val at: Instant) : ImportState()
}"ImportState": {
"description": "The lifecycle state of an import.",
"oneOf": [{ "$ref": "#/components/schemas/Completed" }],
"discriminator": { "propertyName": "type", "mapping": { "completed": "#/components/schemas/Completed" } }
},
"Completed": {
"description": "The import finished without errors.",
"type": "object",
"properties": { "type": { "type": "string", "enum": ["completed"] }, "at": { "type": "string", "format": "date-time" } }
}@get:Description works for the use-site form, as with @Deprecated. An annotation is needed rather than KDoc because KDoc does not survive compilation — and because KDoc is written for maintainers, which is not the same audience as the API's consumers.
That difference in audience is worth making the rule, rather than letting the two drift into saying the same thing twice:
@Descriptioncarries everything a consumer of the API needs. It is the primary, and it is what ships.- KDoc carries only what a maintainer needs and a consumer does not: invariants, why the field exists, gotchas, cross-links to related declarations.
- A property with nothing maintainer-specific to say gets no KDoc. Restating the description is how the two start to disagree.
/** See [trains] for the raw chain this is derived from. */
@Description("The cleaned view of `trains`: overlapping stops between adjacent trains merged away and cancelled stops filtered out.")
val cleanedTrains: List<RuteplanTrainDto>,The cross-link is real maintainer value that an annotation cannot express — KDoc resolves [trains], an annotation argument is plain text. That asymmetry is also why the two can never be quite the same string, and so why keeping both in sync by hand is a losing game: prefer a short KDoc that points, over one that repeats.
Deciding by audience rather than by "avoid duplication" answers the awkward case too. When a fact serves both readers, it belongs in @Description and KDoc stays quiet.
@AllowedValues restricts a property to a fixed set of values, rendering as "enum" on that property. It is for constraints a Kotlin type cannot express — typically the same field allowing different values on each subclass of a sealed hierarchy.
The values live in an AllowedValuesProvider object, referenced by class. Annotation parameters cannot be generic, so a class reference is the only way one annotation can carry typed values of every type. The same object then enforces the constraint at runtime, so the documented set and the checked set cannot drift apart:
object SushiPieces : AllowedValuesProvider<Int> {
override val values = setOf(6, 8, 12)
}
object DumplingPieces : AllowedValuesProvider<Int> {
override val values = setOf(5, 10, 15)
}
@Serializable
@JsonClassDiscriminator("dish")
sealed interface Order {
@Serializable @SerialName("sushi")
data class SushiOrder(@AllowedValues(SushiPieces::class) val pieces: Int) : Order {
init { SushiPieces.requireAllowed(pieces, "pieces") }
}
@Serializable @SerialName("dumplings")
data class DumplingOrder(@AllowedValues(DumplingPieces::class) val pieces: Int) : Order {
init { DumplingPieces.requireAllowed(pieces, "pieces") }
}
}"SushiOrder": {
"type": "object",
"properties": {
"dish": { "type": "string", "enum": ["sushi"] },
"pieces": { "type": "integer", "format": "int32", "enum": [6, 8, 12] }
},
"required": ["dish", "pieces"]
}- Any primitive property:
Int,Long,Short,Byte,Double,Float,Boolean,String,Char, unsigned types, and value classes or contextual types that serialize as one. Each value is encoded with the property's serializer, so it renders the way the property is written on the wire —Kg(1500)as1500, a contextualLocalDateas its string. - Not enum classes or structures: an enum-class property renders as
$ref, and anenumbeside a$refis ignored by OpenAPI 3.0 and most generators, so it is rejected; declare a narrower enum class instead. Lists, maps and objects are rejected too. - Nullable properties:
nullis added to theenum, which sits on the outer schema likedescriptiondoes — beside thetypearray underTYPE_ARRAY, besideanyOfunderANYOF. Without it,{"type": ["integer", "null"], "enum": [5, 10]}would reject thenullthe type admits. Provider values themselves are never null. - Checked at schema generation: the compiler cannot tie the provider's type to the property's, so the schema creator does, and fails with an
IllegalArgumentExceptionnaming the property when the provider is not anobject, is empty, holds values of another type, or when the example uses a value the constraint rejects (it would otherwise be published invalid against its own schema). A property-level@Serializable(with = ...)that changes the wire type is rejected too, since the values could not be rendered as the property writes them. - Documentation, not validation: kotlinx.serialization does not validate against the schema. Call
requireAllowed(value, "name")from aninitblock, as above, to turn a disallowed value into a deserialization failure — and so a400from an http4k body lens.value in SushiPiecesworks too.
@get:AllowedValues works for the use-site form, as with @Description. The annotation must sit on the concrete class's property: one on a sealed interface's abstract val is not inherited by the overrides.
Kotlinx-serialization's compiler plugin generates a descriptor.isInline = true descriptor for @JvmInline value class X(val value: Y). The schema creator unwraps these: the schema for X is the schema for Y. This matters for Liflig services that use inline value classes for type-safe IDs:
@JvmInline value class UserId(override val value: UUID) : UuidEntityId
@Serializable data class User(val id: UserId, val name: String)User.id appears in the schema as {"type": "string", "format": "uuid"} (assuming formatMappings includes UUID), not as a wrapping object. Definition names also don't gain a UserId indirection.
The map key serializer must have kind = PrimitiveKind.STRING. What this means in practice:
Map<String, T>works.Map<UUID, T>works (the standard kotlinx UUID serializer hasPrimitiveKind.STRING). Any custom serializer that writes its value as a JSON string is also fine — what matters is the descriptor'skind, not the underlying Kotlin type.Map<EnumX, T>throws (enum key descriptor hasSerialKind.ENUM).Map<Int, T>and other non-string primitives throw (PrimitiveKind.INT, etc.).Map<UserId, T>whereUserIdis an inline@JvmInline value classthrows — the inline descriptor hasStructureKind.CLASS, even though the runtime representation is a string. Inline value classes are unwrapped in property positions (see above), but the map-key check looks at the declared descriptor kind, not the unwrapped type.
For maps with enum or inline-value-class keys, serialize them as List<{key, value}> records, or use kotlinx-serialization's MapAsArraySerializer for the wire format.
By default, schema definitions are named after the @Serializable class (or @SerialName if present). The overrideDefinitionId parameter on toSchema() lets you rename the top-level definition:
schema.toSchema(myDto, overrideDefinitionId = "CreateUserRequest")This is useful when the same DTO class is used for different endpoints and you want distinct schema names in the OpenAPI document. For sealed classes, only the top-level definition is renamed — subclass definitions keep their original names.
Enums ignore the override. http4k renders an enum query or path parameter by calling toSchema(enumConstants[0], meta.name, null) — it passes the parameter name as the override. Honouring that would key the definition by the parameter (status) rather than the type (TaskStatusDto), and since the same enum is usually also reached through a request or response body, the document would end up with two identical components under different names. An enum always resolves to a named definition from its serial name, so the override has nothing useful to add:
schema.toSchema(TaskStatusDto.OPEN, overrideDefinitionId = "status")
// -> definition "TaskStatusDto", $ref "#/components/schemas/TaskStatusDto"If you genuinely need two differently-named schemas for one enum, declare a second enum type.
The sealedClassStrategy parameter controls the parent definition of a sealed hierarchy. Subclass definitions are the same either way: the discriminator property is required and pinned to the subclass's serial name with a single-value enum.
val schema = KotlinxSerializationJsonSchemaCreator<JsonElement>(
json = KotlinxSerialization,
kotlinxJson = kotlinxJson,
sealedClassStrategy = SealedClassStrategy.ONE_OF,
)| Strategy | Parent definition | Best for |
|---|---|---|
DISCRIMINATED_ONE_OF (default) |
oneOf of $refs plus an OpenAPI discriminator with propertyName and mapping |
Generators that dispatch on the discriminator value |
ONE_OF |
oneOf of $refs only |
Consumers that should rely on plain JSON Schema rather than the OpenAPI-specific discriminator keyword |
Under ONE_OF the branches stay disjoint because each subclass pins the discriminator property. openapi-generator-cli (typescript-fetch) still generates a union of the subclass types, deserializing by checking each branch's pinned discriminator value in turn rather than switching on it. A single-value enum is used for the pin rather than const so the output stays valid under OpenAPI 3.0.
When the schema creator encounters a sealed class field, it needs example instances of the subclasses to generate complete schemas. The sealedClassExampleProvider parameter controls how these are discovered.
The default (DefaultSealedClassExampleProvider) looks for examples in two places:
objectsubclasses (data objects) are used directlydata classsubclasses: looks for acompanion objectwith anexampleproperty
Sealed subtypes nested under the sealed parent are walked through, so leaves at any depth are found. The intermediate sealed type itself needs no companion.
@Serializable
sealed class EventPayload {
@Serializable @SerialName("created")
data class Created(val name: String) : EventPayload() {
companion object {
val example = Created("test-item")
}
}
@Serializable @SerialName("deleted")
data object Deleted : EventPayload()
}If a sealed data class subclass is missing a companion object with an example property, the schema will still generate but without example values for that subclass. There is no compile-time enforcement — make sure to add examples for all data class subclasses used in API contracts.
You can replace this with a custom SealedClassExampleProvider if your DTOs follow a different pattern.
mvn spotless:apply # format code
mvn test # run tests
mvn verify # full build (format check + tests)