mn create-app example.micronaut.micronautguide \
--features=openapi,swagger-ui,validation \
--build=maven \
--lang=java \
--test=junit
Visualize with Swagger-UI an OpenAPI specification of your Micronaut Application
Learn how to generate an OpenAPI Specification of your Micronaut Application at build time and visualize it Swagger-UI
Authors: Sergio del Amo
Micronaut Version: 4.6.3
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:
-
Some time on your hands
-
A decent text editor or IDE (e.g. IntelliJ IDEA)
-
JDK 21 or greater installed with
JAVA_HOME
configured appropriately
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.
-
Download and unzip the source
4. Writing the Application
Create an application using the Micronaut Command Line Interface or with Micronaut Launch.
If you don’t specify the --build argument, Gradle with the Kotlin DSL 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
, swagger-ui
, 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:
<!-- Add the following to your annotationProcessorPaths element -->
<path>
<groupId>io.micronaut.openapi</groupId>
<artifactId>micronaut-openapi</artifactId>
</path>
<dependency>
<groupId>io.micronaut.openapi</groupId>
<artifactId>micronaut-openapi-annotations</artifactId>
<scope>compile</scope>
</dependency>
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:
package example.micronaut;
public enum BuildTool {
GRADLE, MAVEN
}
A guide may be written in multiple languages:
package example.micronaut;
public enum Language {
GROOVY,
JAVA,
KOTLIN
}
Thus, we have several options per guide:
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:
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.
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:
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.
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:
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:
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:
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. Swagger UI
To simplify the visualization of the OpenAPI specification, we are going to use Swagger UI
Swagger UI allows anyone — be it your development team or your end consumers — to visualize and interact with the API’s resources without having any of the implementation logic in place. It’s automatically generated from your OpenAPI (formerly known as Swagger) Specification, with the visual documentation making it easy for back end implementation and client side consumption.
To generate Swagger-UI HTML, create an openapi.properties
file in the root of your project and add:
swagger-ui.enabled=true
You can write a test to verify that Swagger-UI HTML is generated at compile-time.
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 SwaggerUiGeneratedTest {
@Test
void buildGeneratesOpenApi(ResourceLoader resourceLoader) {
assertTrue(resourceLoader.getResource("META-INF/swagger/views/swagger-ui/index.html").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. Expose Swagger-UI
We can expose the Swagger-UI HTML generated at compile-time as a static resource with the following configuration:
micronaut.router.static-resources.swagger-ui.paths=classpath:META-INF/swagger/views/swagger-ui
micronaut.router.static-resources.swagger-ui.mapping=/swagger-ui/**
You can test the Swagger-UI is available:
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 SwaggerUiTest {
@Test
void openApi(@Client("/") HttpClient httpClient) { (2)
BlockingHttpClient client = httpClient.toBlocking();
assertDoesNotThrow(() -> client.exchange("/swagger-ui/index.html"));
}
}
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.8. Home Controller
Next, create a controller that redirects to the swagger-ui endpoint.
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 SWAGGER_UI = UriBuilder.of("/swagger-ui").path("index.html").build();
@Get (2)
@Hidden (3)
HttpResponse<?> home() {
return HttpResponse.seeOther(SWAGGER_UI);
}
}
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:
package example.micronaut;
import io.micronaut.context.annotation.Property;
import io.micronaut.core.util.StringUtils;
import io.micronaut.http.HttpHeaders;
import io.micronaut.http.HttpResponse;
import io.micronaut.http.HttpStatus;
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 testRedirectionToSwaggerUi(@Client("/") HttpClient httpClient) { (3)
BlockingHttpClient client = httpClient.toBlocking();
HttpResponse<?> response = assertDoesNotThrow(() -> client.exchange("/"));
assertEquals(HttpStatus.SEE_OTHER, response.getStatus());
assertNotNull(response.getHeaders().get(HttpHeaders.LOCATION));
assertEquals("/swagger-ui/index.html", response.getHeaders().get(HttpHeaders.LOCATION));
}
@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. |
5. Testing the Application
To run the tests:
./mvnw test
6. Running the Application
To run the application, use the ./mvnw mn:run
command, which starts the application on port 8080.
If you go to http://localhost:8080
, you will see the SwaggerUI visualization of the compile-time generated OpenAPI Specification
7. 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.
|
7.1. GraalVM installation
sdk install java 21.0.5-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:
sdk install java 21.0.2-graalce
7.2. Native executable generation
To generate a native executable using Maven, run:
./mvnw package -Dpackaging=native-image
The native executable is created in the target
directory and can be run with target/micronautguide
.
If you go to http://localhost:8080
, you will see the SwaggerUI visualization of the compile-time generated OpenAPI Specification
8. Next steps
Explore more features with Micronaut Guides.
9. Help with the Micronaut Framework
The Micronaut Foundation sponsored the creation of this Guide. A variety of consulting and support services are available.
10. 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…). |