Generate OpenApi at build time?

Hi all. Is it possible to generate OpenApi Yaml/JSON as part of an sbt build process? Anyone have any examples of this?

I don’t have an example at hand, but you should invoke sbt’s run or runMain (or some other task that runs your code) with a dedicated “main” class which generates the openapi file and writes it to the provided path. You could probably do this after compilation or before packaging.

I have an sbt task defined as

generateOpenApiDoc      :=
  (Runtime / runMain)

that gets invoked with sbt generateOpenApiDoc

OpenApiGenerator mainly consists of

val openApiDocs: OpenAPI = OpenAPIDocsInterpreter().serverEndpointsToOpenAPI().openapi("3.0.3")

Files.write(Paths.get(targetOutputPath),  openApiDocs.toYaml3_0_3.getBytes(StandardCharsets.UTF_8))

I have a complete example repo you can take a look at:

the matapi (materialize API) module is the one you want to look at.
It’s all explained in the README, but LMK if you have any questions :slight_smile:

1 Like

As an alternative, what I’ve seen doing and working quite well is having a “test” that generates the openapi and writes it down.

That way the spec is updated on every pipeline run, but not at every compile.
If you want, you can even check if the output is the same, and fail the test if it’s not (so a sort of overWrite parameter).

1 Like