I was wondering something about the openapi module...
# http4k
a
I was wondering something about the openapi module. I am serving a openapi spec like this:
Copy code
val handler: HttpHandler = routes(
        contract {
            routes += registerCustomerRoute()
            renderer = OpenApi3(
                ApiInfo("My API", "0.0.1")
            )
            this.descriptionPath = "./openapi.json"
        },
        // Bind Swagger UI to another path
        "api/v1/swagger" bind swaggerUiWebjar {
            url = "/openapi.json"
            pageTitle = "My API"
            displayOperationId = true
        },
    )
handler.asServer(Undertow(8080)).start()
So as expected, this gives us a
openapi.json
file on the expected route. However, I want to output this json file as part of the CI/CD workflow to ensure that whatever was the last "approved"
openapi.json
is identical to whatever is generated as part of the CI/CD workflow. I managed ish a function that outputs a json file:
Copy code
fun generateJsonFile() {
    val format = "json"
    val out = "generated/openapi-generated.$format"

    val jsonRenderer = OpenApi3(
        ApiInfo("My API", "0.0.1"),
        Jackson
    )

    val api = contract {
        routes += registerCustomerRoute()
        renderer = jsonRenderer
    }

    val spec = jsonRenderer.description(
        routes = listOf(registerCustomerRoute()),
        contractRoot = PathSegments("/api/v1"),
        security = null,
        tags = emptySet(),
        webhooks = emptyMap()
    )

    val outPath = Path.of(out)
    Files.createDirectories(outPath.parent)
    Files.writeString(outPath, spec.body.toString())
    println("OpenAPI ($format) written to: $out")
}
Is there a built-in way to achieve this? I just want to avoid breaking changes in essence, because we are generating spec from code and I don't want to break the API in the future accidentally.
d
what we do with this is to use an JsonApprovalTest (http4k-testing-approval) and then simply call the swagger endpoint on the app. This will create an approval file with the JSON which you can commit to Git. If you change the contract, the test will break (until you manually approve it)
a
Do you have an example of this?