Generate API documentation in Asciidoc with the generated OpenAPI specification of your Micronaut Application.

Learn how to generate an OpenAPI Specification of your Micronaut Application at build time and generate it as well in Asciidoc format

Authors: Sergio del Amo

Micronaut Version: 4.3.8

1. Getting Started

In this guide, we will create a Micronaut application written in Java.

2. What you will need

To complete this guide, you will need the following:

3. Solution

We recommend that you follow the instructions in the next sections and create the application step by step. However, you can go right to the completed example.

4. Writing the Application

Create an application using the Micronaut Command Line Interface or with Micronaut Launch.

mn create-app example.micronaut.micronautguide \
    --features=openapi,openapi-adoc,validation \
    --build=gradle \
    --lang=java \
    --test=junit
If you don’t specify the --build argument, Gradle is used as the build tool.
If you don’t specify the --lang argument, Java is used as the language.
If you don’t specify the --test argument, JUnit is used for Java and Kotlin, and Spock is used for Groovy.

The previous command creates a Micronaut application with the default package example.micronaut in a directory named micronautguide.

If you use Micronaut Launch, select Micronaut Application as application type and add openapi, openapi-adoc, and validation features.

If you have an existing Micronaut application and want to add the functionality described here, you can view the dependency and configuration changes from the specified features and apply those changes to your application.

4.1. Micronaut OpenAPI

To use Micronaut OpenAPI, add the micronaut-openapi annotation processor and the Micronaut OpenAPI annotations as compile only dependency:

build.gradle
annotationProcessor("io.micronaut.openapi:micronaut-openapi")
implementation("io.micronaut.openapi:micronaut-openapi-annotations")

The micronaut-openapi-annotations dependency brings the Swagger annotations dependency transitively.

4.2. Latest Guide Controller

First, let’s create a controller that exposes the Micronaut Guides information.

4.2.1. Guides Model

We support different build tools per guide:

src/main/java/example/micronaut/BuildTool.java
package example.micronaut;

public enum BuildTool {

    GRADLE, MAVEN
}

A guide may be written in multiple languages:

src/main/java/example/micronaut/Language.java
package example.micronaut;

public enum Language {

    GROOVY,
    JAVA,
    KOTLIN
}

Thus, we have several options per guide:

src/main/java/example/micronaut/Option.java
package example.micronaut;

import io.micronaut.serde.annotation.Serdeable;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;

@Serdeable (1)
public record Option(@NotNull Language language, (2)
                     @NotNull BuildTool buildTool, (2)
                     @NotBlank String url) { (2)
}
1 Declare the @Serdeable annotation at the type level in your source code to allow the type to be serialized or deserialized.
2 Use jakarta.validation.constraints Constraints to ensure the data matches your expectations.

The following Java record represents a Micronaut Guide:

src/main/java/example/micronaut/Guide.java
package example.micronaut;

import io.micronaut.core.annotation.Nullable;
import io.micronaut.serde.annotation.Serdeable;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
import java.time.LocalDate;
import java.util.List;

@Serdeable (1)
public record Guide(@NotBlank String title,
                    @NotBlank String intro,
                    @NotNull @Size(min = 1) List<@NotBlank String> authors, (2)
                    @Nullable List<@NotBlank String> tags,
                    @NotNull @Size(min = 1) List<@NotBlank String> categories,
                    @Schema(format = "yyyy-MM-dd", example = "2018-05-23") @NotNull LocalDate publicationDate, (3)
                    @NotBlank String slug,
                    @NotBlank String url,
                    @NotNull @Size(min = 1) List<@NotNull @Valid Option> options) {
}
1 Declare the @Serdeable annotation at the type level in your source code to allow the type to be serialized or deserialized.
2 Use jakarta.validation.constraints Constraints to ensure the data matches your expectations.
3 You can use the swagger annotation @Schema to customize the generated OpenAPI specification.

4.2.2. Controller

Let’s create a controller for which we will generate an OpenAPI Specification at build time.

src/main/java/example/micronaut/LatestGuidesController.java
package example.micronaut;

import io.micronaut.http.annotation.Controller;
import io.micronaut.http.annotation.Get;
import java.time.LocalDate;
import java.util.Collections;
import java.util.List;

@Controller("/latest") (1)
class LatestGuidesController {

    private static final List<Guide> GUIDES = Collections.singletonList(
            new Guide("Creating your first Micronaut application",
                    "Learn how to create a Hello World Micronaut application with a controller and a functional test.",
                    List.of("Iván López", "Sergio dle Amo"),
                    List.of("junit","getting_started","graalvm"),
                    List.of("Getting Started"),
                    LocalDate.of(2018, 5, 23),
                    "creating-your-first-micronaut-app",
                    "https://guides.micronaut.io/latest/creating-your-first-micronaut-app.html",
                    List.of(new Option(Language.JAVA, BuildTool.GRADLE, "https://guides.micronaut.io/latest/creating-your-first-micronaut-app-gradle-java.html"),
                            new Option(Language.GROOVY, BuildTool.GRADLE, "https://guides.micronaut.io/latest/creating-your-first-micronaut-app-gradle-groovy.html"),
                            new Option(Language.KOTLIN, BuildTool.GRADLE, "https://guides.micronaut.io/latest/creating-your-first-micronaut-app-gradle-kotlin.html"),
                            new Option(Language.JAVA, BuildTool.MAVEN, "https://guides.micronaut.io/latest/creating-your-first-micronaut-app-maven-java.html"),
                            new Option(Language.GROOVY, BuildTool.MAVEN, "https://guides.micronaut.io/latest/creating-your-first-micronaut-app-maven-groovy.html"),
                            new Option(Language.KOTLIN, BuildTool.MAVEN, "https://guides.micronaut.io/latest/creating-your-first-micronaut-app-maven-kotlin.html")
                            ))
    );

    @Get("/guides.json") (2)
    List<Guide> latestGuides() {
        return GUIDES;
    }
}

We could test such a controller with:

src/test/java/example/micronaut/LatestGuidesControllerTest.java
package example.micronaut;

import io.micronaut.http.HttpRequest;
import io.micronaut.http.client.BlockingHttpClient;
import io.micronaut.http.client.HttpClient;
import io.micronaut.http.client.annotation.Client;
import io.micronaut.http.uri.UriBuilder;
import io.micronaut.test.extensions.junit5.annotation.MicronautTest;
import org.junit.jupiter.api.Test;

import java.net.URI;

import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertTrue;

@MicronautTest (1)
class LatestGuidesControllerTest {

    @Test
    void guidesEndpoint(@Client("/") HttpClient httpClient) { (2)
        BlockingHttpClient client = httpClient.toBlocking();
        URI uri = UriBuilder.of("/latest").path("guides.json").build();
        HttpRequest<?> request = HttpRequest.GET(uri);
        String json = assertDoesNotThrow(() -> client.retrieve(request));
        assertTrue(json.contains("2018-05-23"));
    }
}
1 Annotate the class with @MicronautTest so the Micronaut framework will initialize the application context and the embedded server. More info.
2 Inject the HttpClient bean and point it to the embedded server.

4.3. @OpenApiSpecification

The Micronaut OpenAPI integration requires a class to be annotated with @OpenApiSpecification. Modify Application.java and annotate it.

src/main/java/example/micronaut/Application.java
package example.micronaut;

import io.micronaut.runtime.Micronaut;
import io.swagger.v3.oas.annotations.*;
import io.swagger.v3.oas.annotations.info.*;
import io.swagger.v3.oas.annotations.servers.Server;

@OpenAPIDefinition(
    info = @Info(
            title = "micronaut-guides",
            version = "1.0"
    ), servers = @Server(url = "https://guides.micronaut.io")
) (1)
public class Application {

    public static void main(String[] args) {
        Micronaut.run(Application.class, args);
    }
}

4.4. OpenAPI Generated at compile-time

By adding the @OpenApiSpecification annotation to Application, an OpenAPI specification is generated at compile-time. You can test it as follows:

src/test/java/example/micronaut/OpenApiGeneratedTest.java
package example.micronaut;

import io.micronaut.core.io.ResourceLoader;
import io.micronaut.test.extensions.junit5.annotation.MicronautTest;
import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertTrue;

@MicronautTest(startApplication = false) (1)
class OpenApiGeneratedTest {

    @Test
    void buildGeneratesOpenApi(ResourceLoader resourceLoader) {
        assertTrue(resourceLoader.getResource("META-INF/swagger/micronaut-guides-1.0.yml").isPresent());
    }
}
1 Annotate the class with @MicronautTest so the Micronaut framework will initialize the application context. This test does not need the embedded server. Set startApplication to false to avoid starting it.

4.5. Expose the OpenAPI Specification

We can expose the OpenAPI specification generated at compile-time as a static resource with the following configuration:

src/main/resources/application.properties
micronaut.router.static-resources.swagger.paths=classpath:META-INF/swagger
micronaut.router.static-resources.swagger.mapping=/swagger/**

You can test the OpenAPI specification is available:

src/test/java/example/micronaut/OpenApiExposedTest.java
package example.micronaut;

import io.micronaut.http.client.BlockingHttpClient;
import io.micronaut.http.client.HttpClient;
import io.micronaut.http.client.annotation.Client;
import io.micronaut.test.extensions.junit5.annotation.MicronautTest;
import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;

@MicronautTest (1)
class OpenApiExposedTest {

    @Test
    void openApi(@Client("/") HttpClient httpClient) { (2)
        BlockingHttpClient client = httpClient.toBlocking();
        assertDoesNotThrow(() -> client.exchange("/swagger/micronaut-guides-1.0.yml"));
    }
}
1 Annotate the class with @MicronautTest so the Micronaut framework will initialize the application context and the embedded server. More info.
2 Inject the HttpClient bean and point it to the embedded server.

4.6. Micronaut OpenAPI Asciidoc

Micronaut OpenAPI provides a dependency to generate the OpenAPI documentation in Asciidoc.

4.6.1. Micronaut OpenAPI Asciidoc dependency

Add the following dependency:

build.gradle
annotationProcessor("io.micronaut.openapi:micronaut-openapi-adoc")

4.6.2. OpenAPI Asciidoc Generated Test

An OpenAPI specification as Asciidoc is generated at compile-time. You can test it as follows:

src/test/java/example/micronaut/OpenApiAsciidocGeneratedTest.java
package example.micronaut;

import io.micronaut.core.io.ResourceLoader;
import io.micronaut.test.extensions.junit5.annotation.MicronautTest;
import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertTrue;

@MicronautTest(startApplication = false) (1)
class OpenApiAsciidocGeneratedTest {

    @Test
    void buildGeneratesOpenApi(ResourceLoader resourceLoader) {
        assertTrue(resourceLoader.getResource("META-INF/swagger/micronaut-guides-1.0.adoc").isPresent());
    }
}
1 Annotate the class with @MicronautTest so the Micronaut framework will initialize the application context. This test does not need the embedded server. Set startApplication to false to avoid starting it.

4.7. Home Controller

Next, create a controller that redirects to the swagger-ui endpoint.

src/main/java/example/micronaut/HomeController.java
package example.micronaut;

import io.micronaut.http.HttpResponse;
import io.micronaut.http.annotation.Controller;
import io.micronaut.http.annotation.Get;
import io.micronaut.http.uri.UriBuilder;
import io.swagger.v3.oas.annotations.Hidden;
import java.net.URI;

@Controller (1)
class HomeController {

    private final static URI ADOC = UriBuilder.of("/swagger").path("micronaut-guides-1.0.adoc").build();

    @Get (2)
    @Hidden (3)
    HttpResponse<?> home() {
        return HttpResponse.seeOther(ADOC);
    }
}
1 The class is defined as a controller with the @Controller annotation mapped to the path /.
2 The @Get annotation maps the method to an HTTP GET request.
3 If you annotate a route with the swagger annotation @Hidden, the compile-time generated OpenAPI specification does not include it.

Write a test that verifies the redirection and checks that the endpoint is not included in the OpenAPI specification:

src/test/java/example/micronaut/HomeControllerTest.java
package example.micronaut;

import io.micronaut.context.annotation.Property;
import io.micronaut.core.util.StringUtils;
import io.micronaut.http.client.BlockingHttpClient;
import io.micronaut.http.client.HttpClient;
import io.micronaut.http.client.annotation.Client;
import io.micronaut.test.extensions.junit5.annotation.MicronautTest;
import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.*;

@Property(name = "micronaut.http.client.follow-redirects", value = StringUtils.FALSE) (1)
@MicronautTest (2)
class HomeControllerTest {

    @Test
    void homeControllerIsHidden(@Client("/") HttpClient httpClient) {
        BlockingHttpClient client = httpClient.toBlocking();
        String yml = assertDoesNotThrow(() -> client.retrieve("/swagger/micronaut-guides-1.0.yml"));
        assertFalse(yml.contains("operationId: home")); (4)
    }
}
1 Annotate the class with @Property to supply configuration to the test.
2 Annotate the class with @MicronautTest so the Micronaut framework will initialize the application context and the embedded server. More info.
3 Inject the HttpClient bean and point it to the embedded server.
4 The root endpoint is not included in the OpenAPI specification.

The hidden path is not included in the asciidoc file:

src/test/java/example/micronaut/HomeControllerHiddenAsciidocTest.java
package example.micronaut;

import io.micronaut.core.io.ResourceLoader;
import io.micronaut.test.extensions.junit5.annotation.MicronautTest;
import org.junit.jupiter.api.Test;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Optional;

import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;

@MicronautTest(startApplication = false) (1)
class HomeControllerHiddenAsciidocTest {

    @Test
    void homeControllerIsHidden(ResourceLoader resourceLoader) throws IOException {
        Optional<InputStream> adocInputStream = resourceLoader.getResourceAsStream("META-INF/swagger/micronaut-guides-1.0.adoc");
        assertTrue(adocInputStream.isPresent());
        String adoc = new String(adocInputStream.get().readAllBytes(), StandardCharsets.UTF_8);
        assertFalse(adoc.contains("=== __GET__ `/`"));
    }
}

5. Testing the Application

To run the tests:

./gradlew test

Then open build/reports/tests/test/index.html in a browser to see the results.

6. Running the Application

To run the application, use the ./gradlew run command, which starts the application on port 8080.

If you go to http://localhost:8080, you will see the Asciidoc version of the compile-time generated OpenAPI Specification

7. GraalVM Resource Configuration

We need the following configuration to access resources in Native Image

By default, the native-image builder will not integrate any of the resources that are on the classpath into the native executable.

Create a new file src/main/resources/META-INF/native-image/example.micronaut.micronautguide/resource-config.json:

src/main/resources/META-INF/native-image/example.micronaut.micronautguide/resource-config.json
{
  "resources": {
    "includes": [
      {"pattern": "META-INF/swagger/micronaut-guides-1.0.adoc$"}
    ]
  }
}

8. Generate a Micronaut Application Native Executable with GraalVM

We will use GraalVM, the polyglot embeddable virtual machine, to generate a native executable of our Micronaut application.

Compiling native executables ahead of time with GraalVM improves startup time and reduces the memory footprint of JVM-based applications.

Only Java and Kotlin projects support using GraalVM’s native-image tool. Groovy relies heavily on reflection, which is only partially supported by GraalVM.

8.1. GraalVM installation

The easiest way to install GraalVM on Linux or Mac is to use SDKMan.io.

Java 17
sdk install java 17.0.8-graal
Java 17
sdk use java 17.0.8-graal

For installation on Windows, or for manual installation on Linux or Mac, see the GraalVM Getting Started documentation.

The previous command installs Oracle GraalVM, which is free to use in production and free to redistribute, at no cost, under the GraalVM Free Terms and Conditions.

Alternatively, you can use the GraalVM Community Edition:

Java 17
sdk install java 17.0.8-graalce
Java 17
sdk use java 17.0.8-graalce

8.2. Native executable generation

To generate a native executable using Gradle, run:

./gradlew nativeCompile

The native executable is created in build/native/nativeCompile directory and can be run with build/native/nativeCompile/micronautguide.

It is possible to customize the name of the native executable or pass additional parameters to GraalVM:

build.gradle
graalvmNative {
    binaries {
        main {
            imageName.set('mn-graalvm-application') (1)
            buildArgs.add('--verbose') (2)
        }
    }
}
1 The native executable name will now be mn-graalvm-application
2 It is possible to pass extra arguments to build the native executable

If you go to http://localhost:8080, you will see the Asciidoc version of the compile-time generated OpenAPI Specification

9. Next steps

Explore more features with Micronaut Guides.

10. Help with the Micronaut Framework

The Micronaut Foundation sponsored the creation of this Guide. A variety of consulting and support services are available.

11. License

All guides are released with an Apache license 2.0 license for the code and a Creative Commons Attribution 4.0 license for the writing and media (images…​).