Generating AsciiDoc from OpenAPI.yml

Sometimes changes to a library are made so easily that it’s not really worth talking about. The Maven Plugin from posts Build Automatisierung mit eigenen Mojos verbessern and Trivial Pursuit – API MarkDown generates AsciiDoc documentation from simple OpenAPI descriptions. So far, the Maven Plugin uses a JSON description as input format. Since the YAML representation is used more frequently, its support would also be desirable.

Before interested readers turn to the Maven Plugin, a warning should be issued here. The starting point of the implementation was the demonstration of how easily an OpenAPI definition can be read and processed with Jackson. For this reason, the plugin only supports a subset of the schema descriptions in OpenAPI. Just as much as the YAGNI approach required for use at the time.

What is the best way to read YAML descriptions if all the work has been done by Jackson so far? The answer is quite simple, we continue to use Jackson but also use an extension.

<dependency>
  <groupId>com.fasterxml.jackson.dataformat</groupId>
  <artifactId>jackson-dataformat-yaml</artifactId>
  <version>2.17.1</version>
</dependency>

Although the two formats JSON and YAML differ considerably in their syntax, the data structures described are identical. Therefore, the YAML extension for Jackson can read the YAML syntax and pass it on to Jackson like a JSON event stream. The central method for reading the OpenAPI description changes minimally.

private ApiDescription getApiDescription(Path inputPath, Charset charset) throws MojoExecutionException {
  try {
    String content = Files.readString(inputPath, charset);
    ObjectMapper mapper = content.startsWith("{") ? new ObjectMapper() : new ObjectMapper(new YAMLFactory());
    return mapper.configure(FAIL_ON_UNKNOWN_PROPERTIES, false).readValue(content, ApiDescription.class);
  } catch (IOException e) {
    throw new MojoExecutionException("Cannot read API description: " + e.getMessage());
  }
}

The ObjectMapper is now generated depending on the input. If the input starts with a curly bracket, then it must be an OpenAPI description in JSON format. In this case, the ObjectMapper is created with the parameterless constructor. In the other case, it is obviously the YAML format and the ObjectMapper is created with a YAMLFactory as a parameter. This means that the implementation is already complete and the Maven Plugin can process OpenAPI definitions in YAML format.

Leave a Comment