-
Notifications
You must be signed in to change notification settings - Fork 34
Types and Schemas
Usually json-schemas for request and response bodies, headers and parameters are generated automatically from types specified directly at the route.
As generic types
body<MyExampleData>(/*...*/)
queryParameter<String>(/*...*/)
header<List<String>>(/*...*/)
//...
As KTypes
body(typeof<MyExampleData>(), /*...*/)
queryParameter(typeof<String>(), /*...*/)
header(typeof<List<String>>(), /*...*/)
//...
As a Swagger-Schema
body(Schema<Any>().also {
it.type = "object"
//...
}, /*...*/)
queryParameter(Schema<Any>().also {
it.type = "string"
}, /*...*/)
header(Schema<Any>().also {
it.type = "array"
//...
}, /*...*/)
//...
In addition, custom and "global" schemas can be defined in the schema-section of the plugin config and then be referenced by multiple routes by their schema-ids.
Defining global schemas
install(SwaggerUI) {
schemas {
// register new schema with the id "example-schema-1" and a generic type
schema<MyExampleData("example-schema-1")
// register new schema with the id "example-schema-2" and a KType
schema("example-schema-2", typeof<String>())
// register new schema with the id "example-schema-3" and a swagger-schema
schema("example-schema-3", Schema<Any>().also {
it.type = "array"
//...
})
}
}
Referencing global schemas
import io.github.smiley4.ktorswaggerui.data.ref
body(ref("example-schema-1"), /*...*/)
queryParameter(ref("example-schema-2"), /*...*/)
header(ref("example-schema-2"), /*...*/)
//...
Schemas and types can be combined to created variations without having to create new classes. Available additional composite operations are array
and anyOf
array
Creates a schema of an array containing items of the specified type or schema.
import io.github.smiley4.ktorswaggerui.data.array
body(array<MyExampleData>())
//...
anyOf
Creates a schema that describes any one of the specified types or schemas.
import io.github.smiley4.ktorswaggerui.data.anyOf
body(anyOf(typeOf<MyExampleData>(), typeOf<MyOtherData>() /*, ...*/))
//...
nesting
The operations array
and anyOf
as well as ref
and type
can be combined and nested to create more complex variations.
body(
anyOf(
array<String>(),
anyOf(
ref("my-schema"),
type<MyExampleData>()
),
)
)
Types can be overwritten with own provided schemas or other types.
install(SwaggerUI) {
schemas {
// overwrite type "List<Int>" with an array of either floats or integer
overwrite<List<Number>(
array(
anyOf(
typeof<Float>(),
typeof<Int>()
)
)
),
// overwrite type "File" with custom schema for binary data
overwrite<File>(Schema<Any>().also {
it.type = "string"
it.format = "binary"
})
}
}
When a body or parameter in a request or response defines a schema of a type that is overwritten in the config, the other given type or schema will be used instead.
- Getting Started
- Configuration
- Documenting Routes
- Multiple Api-Specs
- Examples
- Changelog
Documentation for previous versions: