Skip to content

Koriit/ktor-controllers-openapi

Repository files navigation

Ktor Controllers OpenAPI

Build CodeFactor ktlint

Maven Central GitHub

Warning
From version 0.5.0 all package names have been renamed to match new artifact group id.

Support for OpenAPI3 in ktor-controllers.

The idea is to validate your OpenAPI spec against your code instead of generating it from your code.

Warning
This library is Work In Progress. It doesn’t support all relevant elements of OpenAPI specification like oauth, callback or encoding yet. However, all structural elements should be supported.

Example

install(Routing) {
    val openapi = {}.javaClass.getResourceAsStream("/openapi.yaml").reader().readText()

    openAPIController(openapi)
    swaggerUIController()
}

Testing

val server = TestApplicationEngine(serverConfig())
server.start()

LOG.info("Analyzing Ktor server...")
val analyzer = KtorOpenAPIAnalyzer(
        ktor = server.application,
        basePaths = listOf("/api"),
        defaultHeaders = listOf(HttpHeader(XRequestId)),
        defaultErrorType = ApiError::class
)

val source = analyzer.analyze()
server.stop(0L, 0L, TimeUnit.MILLISECONDS)

LOG.info("Reading OpenAPI spec...")
val doc = OpenAPIReader().load({}.javaClass.getResourceAsStream("/openapi.yaml"))

LOG.info("Validating spec...")
val errors = OpenAPIMatcher().match(doc, source)

if (errors.isNotEmpty()) {
    LOG.info("Result of server analysis:\n{}", source)

    errors.forEach {
        LOG.error(it)
    }

    fail("There are ${errors.size} validation errors!")

} else {
    LOG.info("OK!")
}