### Hello World Controller Example Source: https://github.com/micronaut-projects/micronaut-openapi/blob/7.0.x/src/main/docs/guide/controllers.adoc This example demonstrates how Micronaut generates an OpenAPI definition from a simple controller. ```APIDOC ## GET /hello/{name} ### Description This endpoint greets a person by name. ### Method GET ### Endpoint /hello/{name} ### Parameters #### Path Parameters - **name** (string) - Required - The person's name ### Responses #### Success Response (200) - **string** - The greeting ``` -------------------------------- ### Versioned Controller Example Source: https://github.com/micronaut-projects/micronaut-openapi/blob/7.0.x/src/main/docs/guide/versionsAndGroups/versions.adoc Example Java controller demonstrating versioned endpoints using the @Version annotation. ```APIDOC ## VersionedController.java This Java code defines a controller with versioned endpoints for GET and POST requests to '/hello', and a common POST endpoint to '/common'. It also includes a nested DTO class `UserDto`. ``` -------------------------------- ### Hello World Controller Example Source: https://github.com/micronaut-projects/micronaut-openapi/blob/7.0.x/src/main/docs/guide/controllers.adoc This Java class serves as an example controller. Micronaut uses its annotations and Javadoc comments to generate the OpenAPI definition. ```java package io.micronaut.configuration.openapi.docs.controllers; import io.micronaut.http.annotation.Controller; import io.micronaut.http.annotation.Get; import io.micronaut.http.annotation.PathVariable; /** * @author Defeated * @since 1.0 */ @Controller("/hello/{name}") public class HelloController { /** * @param name the name * @return greeting */ @Get public String index(@PathVariable final String name) { return "Hello " + name + "!"; } } ``` -------------------------------- ### Greeting Controller Example Source: https://context7.com/micronaut-projects/micronaut-openapi/llms.txt Example of a Micronaut controller using Swagger annotations to define an OpenAPI operation for greeting a person. ```APIDOC ## GET /greetings/{name} ### Description A friendly greeting is returned. ### Method GET ### Endpoint /greetings/{name} ### Parameters #### Path Parameters - **name** (string) - Required - The name of the person ### Responses #### Success Response (200) - **string** - A friendly greeting #### Error Response (400) - **description**: Invalid Name Supplied #### Error Response (404) - **description**: Person not found ``` -------------------------------- ### Example Generated Swagger Output Source: https://github.com/micronaut-projects/micronaut-openapi/blob/7.0.x/src/main/docs/guide/controllers.adoc This is the resulting OpenAPI 3.0.1 YAML definition generated from the HelloController example. It details the API's paths, operations, parameters, and responses. ```yaml openapi: 3.0.1 info: title: Hello World description: My API contact: name: Fred url: https://gigantic-server.com email: Fred@gigagantic-server.com license: name: Apache 2.0 url: https://foo.bar version: "0.0" paths: /hello/{name}: get: description: "" operationId: index parameters: - name: name in: path description: The person's name required: true schema: type: string responses: 200: description: The greeting content: text/plain: schema: type: string ``` -------------------------------- ### Example @OpenAPIDefinition Usage Source: https://github.com/micronaut-projects/micronaut-openapi/blob/7.0.x/src/main/docs/guide/openApiDefinition.adoc Annotate your Application class or another class to define global components and common OpenAPI information. ```java package example.micronaut.configuration.openapi.docs; import io.micronaut.openapi.annotation.OpenAPIDefinition; import io.micronaut.openapi.annotation.info.Contact; import io.micronaut.openapi.annotation.info.Info; import io.micronaut.openapi.annotation.info.License; import io.micronaut.openapi.annotation.servers.Server; @OpenAPIDefinition( info = @Info( title = "the title", version = "0.0", description = "My API", license = @License(name = "Apache 2.0", url = "https://foo.bar"), contact = @Contact(url = "https://gigantic-server.com", name = "Fred", email = "Fred@gigagantic-server.com") ), servers = { @Server(url = "http://localhost:8080", description = "Development server") } ) public class Application { public static void main(String[] args) { // ... } } ``` -------------------------------- ### OpenAPI Properties File Example Source: https://github.com/micronaut-projects/micronaut-openapi/blob/7.0.x/src/main/docs/guide/configuration/propertiesFileConfiguration.adoc Specify OpenAPI processing configuration in the `openapi.properties` file. Use `micronaut.openapi.config.file` system property for custom locations. ```properties micronaut.openapi.property.naming.strategy=KEBAB_CASE micronaut.openapi.target.file=myspecfile.yml ... ``` -------------------------------- ### Example Generated Swagger Output Source: https://github.com/micronaut-projects/micronaut-openapi/blob/7.0.x/src/main/docs/guide/swaggerAnnotations.adoc This YAML output demonstrates the structure generated by applying Swagger Annotations to a Micronaut controller. ```APIDOC ## GET /greetings/{name} ### Description A friendly greeting is returned ### Method GET ### Endpoint /greetings/{name} ### Parameters #### Path Parameters - **name** (string) - Required - The name of the person ### Responses #### Success Response (200) - (string) - OK #### Error Responses - **400** - Invalid Name Supplied - **404** - Person not found ``` -------------------------------- ### Example Generated Swagger Output Source: https://github.com/micronaut-projects/micronaut-openapi/blob/7.0.x/src/main/docs/guide/swaggerAnnotations.adoc This YAML output demonstrates the structure of an OpenAPI 3.0.1 definition generated using Swagger annotations. ```yaml openapi: 3.0.1 info: title: Hello World description: My API contact: name: Fred url: https://gigantic-server.com email: Fred@gigagantic-server.com license: name: Apache 2.0 url: https://foo.bar version: "0.0" paths: /greetings/{name}: get: tags: - greeting summary: Greets a person description: A friendly greeting is returned operationId: greetings parameters: - name: name in: path description: The name of the person required: true schema: minLength: 1 type: string responses: 200: description: OK content: text/plain: schema: type: string 400: description: Invalid Name Supplied 404: description: Person not found ``` -------------------------------- ### Automatic Tag Generation Example Source: https://context7.com/micronaut-projects/micronaut-openapi/llms.txt Demonstrates automatic tag generation from a controller's Javadoc and class name. The tag 'user-operations' is derived from the controller's name and its Javadoc. ```java /** * User main operations. */ @Controller public class UserOperationsController { @Get("/read/{id}") public String read(String id) { return "OK!"; } } // Tag "user-operations" is auto-generated with description from Javadoc ``` -------------------------------- ### Multipart Request Example Source: https://github.com/micronaut-projects/micronaut-openapi/blob/7.0.x/src/main/docs/guide/spring/springWithWrappedRequestData.adoc This snippet shows the OpenAPI specification for a controller method handling multipart/form-data requests with wrapped data. It includes path parameters, query parameters, and a request body with file and string properties. ```APIDOC ## POST /my-api/testMultipart/{pathVar} ### Description Handles multipart requests with wrapped data, including path variables, query parameters, and form data. ### Method POST ### Endpoint /my-api/testMultipart/{pathVar} ### Parameters #### Path Parameters - **pathVar** (string) - Required - This is path variable #### Query Parameters - **queryVar** (string) - Required - This is request param #### Request Body - **fileName** (string) - Required - This is fileName request body part - **file** (string) - Required - This is file request body part (format: binary) ### Request Example { "example": "{\"fileName\": \"example.txt\", \"file\": \"binary_content\"}" } ### Response #### Success Response (200) - **description** (string) - testMultipart 200 response ``` -------------------------------- ### Versioned Controller Example Source: https://github.com/micronaut-projects/micronaut-openapi/blob/7.0.x/src/main/docs/guide/versionsAndGroups/versions.adoc Defines a controller with versioned endpoints using the @Version annotation. Supports different HTTP methods for the same path based on version. ```java @Controller("/versioned") public class VersionedController { @Version("1") @Get("/hello") public String helloV1() { return "helloV1"; } @Version("2") @Post("/hello") public String helloV2(UserDto userDto) { return "helloV2"; } @Post("/common") public String common() { return null; } public static class UserDto { public String name; public int age; public String secondName; @NotNull public String address; } } ``` -------------------------------- ### Pet POJO Schema Customization Source: https://context7.com/micronaut-projects/micronaut-openapi/llms.txt Example of customizing a POJO schema using @Schema annotations for OpenAPI generation. ```APIDOC ## Schema: MyPet ### Description Pet description ### Fields - **type** (PetType) - Description: Not specified - **age** (integer) - Description: Pet age, maximum: 20 - **name** (string) - Description: Pet name, maxLength: 20 ``` -------------------------------- ### Enable OpenAPI Views Generation Source: https://github.com/micronaut-projects/micronaut-openapi/blob/7.0.x/src/main/docs/guide/openApiViews/viewsGenerationWithPropertiesFile.adoc Configure `micronaut.openapi.views.spec` in your properties file to enable various OpenAPI views and customize their settings. This example enables Swagger UI, ReDoc, OpenAPI Explorer, Scalar, and RapiDoc, also setting RapiDoc's background color, text color, and endpoint sorting. ```properties micronaut.openapi.views.spec = swagger-ui.enabled=true,\ redoc.enabled=true, \ openapi-explorer.enabled=true, \ scalar.enabled=true, \ rapidoc.enabled=true, \ rapidoc.bg-color=#14191f, \ rapidoc.text-color=#aec2e0, \ rapidoc.sort-endpoints-by=method ``` -------------------------------- ### Configure Custom Accessor Prefixes with @AccessorsStyle Source: https://github.com/micronaut-projects/micronaut-openapi/blob/7.0.x/src/main/docs/guide/micronautOpenApiAnnotations/accessorsStyle.adoc Use @AccessorsStyle to define custom prefixes for getters and setters when the default 'get' and 'set' are not suitable. This example configures no prefixes for a fluent API style. ```java @Introspected @AccessorsStyle(readPrefixes = "", writePrefixes = "") // <1> class Person { private String name; private Integer debtValue; private Integer totalGoals; Person(String name, Integer debtValue, Integer totalGoals) { this.name = name; this.debtValue = debtValue; this.totalGoals = totalGoals; } public String name() { // <2> return name; } public Integer debtValue() { return debtValue; } public Integer totalGoals() { return totalGoals; } public void name(String name) { // <2> this.name = name; } public void debtValue(Integer debtValue) { this.debtValue = debtValue; } public void totalGoals(Integer totalGoals) { this.totalGoals = totalGoals; } } ``` -------------------------------- ### Initialize Redoc Documentation Source: https://github.com/micronaut-projects/micronaut-openapi/blob/7.0.x/openapi/src/main/resources/templates/redoc/index.html This script initializes Redoc by loading the standalone JavaScript file and then rendering the OpenAPI specification. It dynamically determines the context path from cookies or URL parameters to ensure correct loading. ```javascript const extract = function(v) { return decodeURIComponent(v.replace(/(?:^|.\*;\s extit{contextPath}\s extit{=}\s extit{(\^;\}\*).\*$|^.\*$/, "$1")); } const cookie = extract(document.cookie); contextPath = cookie === '' ? extract(window.location.search.substring(1)) : cookie; if (!isSafeContextPath(contextPath)) { contextPath = ''; } const head = document.getElementsByTagName('head')[0]; const redocJs = script(contextPath + "{{redoc.js.url.prefix}}redoc.standalone.js", head, true); redocJs.onload = function () { Redoc.init(contextPath + '{{specURL}}'); } ``` -------------------------------- ### Initialize RapiDoc with Context Path Handling Source: https://github.com/micronaut-projects/micronaut-openapi/blob/7.0.x/openapi/src/main/resources/templates/rapidoc/index.html This script initializes RapiDoc, extracts the API context path from cookies or URL parameters, and applies it to the loaded specification. It ensures the context path is safe and correctly formatted. ```javascript window.addEventListener('DOMContentLoaded', () => { const docEl = document.getElementById('rapidoc'); docEl.addEventListener('before-try', (e) => { e.detail.request.headers.append('AAA-BBB', 'CCC DDDD'); }); }); const extract = function(v) { return decodeURIComponent(v.replace(/(?:^|.\*;\\s\*)contextPath\s\*=\s\*([^;]\\*).\\|$|^.\*$/, "$1")); } const cookie = extract(document.cookie) contextPath = cookie === '' ? extract(window.location.search.substring(1)) : cookie; if (!isSafeContextPath(contextPath)) { contextPath = ''; } const head = document.getElementsByTagName('head')[0]; const rapidocJs = script(contextPath + "{{rapidoc.js.url.prefix}}rapidoc-min.js", head, true) rapidocJs.onload = function () { const rapidoc = document.getElementById('rapidoc') if (contextPath !== '') { rapidoc.addEventListener('spec-loaded', e => { e.detail.tags.forEach(tag => tag.paths.forEach(path => path.path = contextPath + path.path)); rapidoc.requestUpdate(); }); } rapidoc.setAttribute('spec-url', contextPath + '{{specURL}}'); } ``` -------------------------------- ### Enable and Configure OpenAPI Views Source: https://github.com/micronaut-projects/micronaut-openapi/blob/7.0.x/src/main/docs/guide/openApiViews/viewsGenerationWithSystemProperties.adoc Set this system property to enable and configure OpenAPI views. The string syntax is a series of comma-separated key-value pairs. ```commandline -Dmicronaut.openapi.views.spec=redoc.enabled=true,rapidoc.enabled=true,openapi-explorer.enabled=true,swagger-ui.enabled=true,swagger-ui.theme=flattop ``` -------------------------------- ### Logout Endpoint Source: https://context7.com/micronaut-projects/micronaut-openapi/llms.txt Defines a GET endpoint for user logout, returning a 302 redirect. ```APIDOC ## GET /logout ### Description Logs out the user and redirects. ### Method GET ### Endpoint /logout ### Responses #### Success Response (302) - description: Redirect ``` -------------------------------- ### Initialize OpenAPI Explorer with CSS and JS Source: https://github.com/micronaut-projects/micronaut-openapi/blob/7.0.x/openapi/src/main/resources/templates/openapi-explorer/index.html Loads necessary CSS and JavaScript files for the OpenAPI Explorer. Ensures the explorer is correctly styled and functional. ```javascript const extract = function(v) { return decodeURIComponent(v.replace(/(?:^|.\*;\\s\*)contextPath\s\*=\s\*([^;]*)'.*$|^.*$/, "$1")); } const cookie = extract(document.cookie) contextPath = cookie === '' ? extract(window.location.search.substring(1)) : cookie; if (!isSafeContextPath(contextPath)) { contextPath = ''; } const openApiExplorer = document.getElementById('openapi-explorer'); const head = document.getElementsByTagName('head')[0] link(contextPath + "{{openapi-explorer.js.url.prefix}}default.min.css", head, "text/css", "stylesheet") link(contextPath + "{{openapi-explorer.js.url.prefix}}bootstrap.min.css", head, "text/css", "stylesheet", "anonymous") link(contextPath + "{{openapi-explorer.js.url.prefix}}font-awesome.min.css", head, "text/css", "stylesheet") const openapiExplorerJs = script(contextPath + "{{openapi-explorer.js.url.prefix}}openapi-explorer.min.js", head, "module", true) openapiExplorerJs.onload = function () { let specUrl = '{{specURL}}'; if (contextPath !== '') { specUrl = contextPath + '{{specURL}}'; openApiExplorer.setAttribute('spec-url', specUrl); openApiExplorer.addEventListener('spec-loaded', e => { e.detail.tags.forEach(tag => tag.paths.forEach(path => path.path = contextPath + path.path)); openApiExplorer.requestUpdate(); }); } openApiExplorer.setAttribute('spec-url', specUrl); document.addEventListener('DOMContentLoaded', async () => { const specUrl = document.getElementById('specUrl'); const currentSpecUrl = new URLSearchParams(window.location.search); const newSpecUrl = currentSpecUrl.get('specUrl') || currentSpecUrl.get('url') || currentSpecUrl.get('spec'); if (newSpecUrl) { document.getElementsByTagName("openapi-explorer")[0].setAttribute('spec-url', newSpecUrl); specUrl.value = newSpecUrl; } const loadButton = document.getElementById('loadButton'); loadButton.addEventListener('click', () => { try { const newUrl = new URL(window.location); newUrl.searchParams.set('url', specUrl.value); window.location.assign(newUrl.toString()); document.getElementsByTagName("openapi-explorer")[0].setAttribute('spec-url', specUrl.value); } catch (error) { console.error('Failed to set spec url into url address bar', error); } }); }); } ``` -------------------------------- ### Enable ReDoc View Source: https://context7.com/micronaut-projects/micronaut-openapi/llms.txt Configuration to enable the ReDoc view for OpenAPI documentation with sorting options. ```APIDOC ## Configuration: openapi.properties ### Description Enables ReDoc with alphabetical sorting of properties and download button. ```properties micronaut.openapi.views.spec=redoc.enabled=true, redoc.sort-props-alphabetically=true, redoc.hide-download-button=false ``` ## Configuration: application.yml ### Description Exposes ReDoc at `/redoc/**`. ```yaml micronaut: router: static-resources: redoc: paths: classpath:META-INF/swagger/views/redoc mapping: /redoc/** ``` ``` -------------------------------- ### Schema Annotation Resolution Example Source: https://github.com/micronaut-projects/micronaut-openapi/blob/7.0.x/src/main/docs/guide/swaggerAnnotations/schemasAnnotationResolution.adoc Demonstrates how Micronaut resolves @Schema annotations. It prioritizes property-level annotations over type-level ones. ```java import io.swagger.v3.oas.annotations.media.Schema; @Schema(description="Pet") // <1> class Pet { } class Owner { private Pet cat; private Pet dog; public Pet getCat() { // <2> return cat; } @Schema(name="MyPet", description="This is my pet") // <3> public Pet getDog() { return dog; } } ``` -------------------------------- ### Expose OpenAPI YAML via Static Resources Source: https://github.com/micronaut-projects/micronaut-openapi/blob/7.0.x/src/main/docs/guide/exposingSwaggerOutput.adoc Add this configuration to your application to expose the OpenAPI YAML output. Access it at `/swagger/hello-world-0.0.yml`. ```yaml micronaut: router: static-resources: swagger: paths: classpath:META-INF/swagger mapping: /swagger/** ``` -------------------------------- ### Controller with Manual Tag Annotation Source: https://github.com/micronaut-projects/micronaut-openapi/blob/7.0.x/src/main/docs/guide/tagsGeneration.adoc Example of a controller where tags are manually set using the `@Tag` annotation. This is the traditional approach before auto-generation. ```java /** * User main operations. */ @Tag("user-operations") // don't need to add this annotation anymore @Controller public class UserOperationsController { @Get("/read/{id}") public String read(String id) { return "OK!"; } @Post("/save/{id}") public String save2(String id, Object body) { return "OK!"; } @Post("/save") public String save(Object body) { return "OK!"; } } ``` -------------------------------- ### Set Server Context Path at Runtime Source: https://context7.com/micronaut-projects/micronaut-openapi/llms.txt Configure the server context path at runtime using application.yml. This approach allows for dynamic path configuration. ```yaml micronaut: server: context-path: /api ``` -------------------------------- ### OpenAPI Properties Expansion Example Source: https://github.com/micronaut-projects/micronaut-openapi/blob/7.0.x/src/main/docs/guide/configuration/propertiesFileConfiguration.adoc Properties prefixed with `micronaut.openapi.expand` are expanded at compile time. These expanded properties can be used as placeholders in OpenAPI definitions. ```properties micronaut.openapi.expand.api.version=v1.1 micronaut.openapi.expand.openapi.description=A nice API ``` -------------------------------- ### Configure Schema Postfix with System Properties Source: https://github.com/micronaut-projects/micronaut-openapi/blob/7.0.x/src/main/docs/guide/schemaDecorators.adoc Define schema postfixes via system properties using the `-Dmicronaut.openapi.schema-postfix.=` format. A project recompile is required after changes. ```bash -Dmicronaut.openapi.schema-postfix.org.api.v1_0_0=1_0_0 -Dmicronaut.openapi.schema-postfix.org.api.v2_0_0=2_0_0 ``` -------------------------------- ### Initialize Swagger UI Bundle Source: https://github.com/micronaut-projects/micronaut-openapi/blob/7.0.x/openapi/src/main/resources/templates/swagger-ui/index.html This snippet initializes the Swagger UI bundle, loading the API specification and setting up presets and plugins. It handles the asynchronous loading of Swagger UI standalone preset if needed. ```javascript const extract = function(v) { return decodeURIComponent(v.replace(/(?:^|.\*;\\s\* )contextPath\\s\*=\\s\*(\[^;\]\*).\*$|^.\*$/, "$1")); }; const cookie = extract(document.cookie); contextPath = cookie === '' ? extract(window.location.search.substring(1)) : cookie; if (!isSafeContextPath(contextPath)) { contextPath = ''; } const head = document.getElementsByTagName('head')[0] link(contextPath + "{{swagger-ui.js.url.prefix}}swagger-ui.css", head, "text/css", "stylesheet") link(contextPath + "{{swagger-ui.js.url.prefix}}favicon-16x16.png", head, "image/png", "icon", "16x16") link(contextPath + "{{swagger-ui.js.url.prefix}}favicon-32x32.png", head, "image/png", "icon", "32x32") {{swagger-ui.theme}} {{rapipdf.script}} window.onload = function() { const swaggerUiBundle = script(contextPath + "{{swagger-ui.js.url.prefix}}swagger-ui-bundle.js", head) const swaggerUiStandalonePreset = script(contextPath + "{{swagger-ui.js.url.prefix}}swagger-ui-standalone-preset.js", head) swaggerUiBundle.onload = function () { if (typeof (SwaggerUIStandalonePreset) == "undefined") { swaggerUiStandalonePreset.onload = function () { initializeSwaggerUI(); }; } else { initializeSwaggerUI() } }; }; function initializeSwaggerUI() { const f = contextPath === '' ? undefined : () => { return { statePlugins: { spec: { wrapActions: { updateJsonSpec: (oriAction) => (...args) => { let [spec] = args; if (spec && spec.paths) { const newPaths = {}; Object.entries(spec.paths).forEach(([path, value]) => newPaths[contextPath + path] = value); spec.paths = newPaths; } oriAction(...args); } } } } }; }; const ui = SwaggerUIBundle({ url: contextPath + '{{specURL}}', dom_id: '#swagger-ui', presets: [ SwaggerUIBundle.presets.apis, SwaggerUIStandalonePreset ], plugins: [ SwaggerUIBundle.plugins.DownloadUrl, f ], {{swagger-ui.primaryName}} {{swagger-ui.urls}} {{swagger-ui.attributes}} }); {{swagger-ui.oauth2}} window.ui = ui; {{rapipdf.specurl}} } ``` -------------------------------- ### Enable RapiDoc View Source: https://context7.com/micronaut-projects/micronaut-openapi/llms.txt Configure OpenAPI properties to enable the RapiDoc view with custom styling and sorting options. ```properties # openapi.properties micronaut.openapi.views.spec=rapidoc.enabled=true, rapidoc.bg-color=#14191f, rapidoc.text-color=#aec2e0, rapidoc.sort-endpoints-by=method, rapidoc.render-style=read ``` -------------------------------- ### Generated OpenAPI Specification with Auto-Generated Tags Source: https://github.com/micronaut-projects/micronaut-openapi/blob/7.0.x/src/main/docs/guide/tagsGeneration.adoc Example of an OpenAPI specification where tags are automatically generated from controller class names and descriptions are derived from Javadoc comments. ```yaml openapi: 3.0.1 info: title: swagger version: "1.0" tags: - name: user-operations description: User main operations. paths: /read/{id}: get: tags: - user-operations operationId: read parameters: - name: id in: path schema: type: string responses: '200': description: Ok /save/{id}: post: tags: - user-operations operationId: save2 parameters: - name: id in: path schema: type: string requestBody: content: application/json: schema: type: object responses: '200': description: Ok /save: post: tags: - user-operations operationId: save requestBody: content: application/json: schema: type: object responses: '200': description: Ok ``` -------------------------------- ### Enable ReDoc View Source: https://context7.com/micronaut-projects/micronaut-openapi/llms.txt Configure OpenAPI properties to enable the ReDoc view. This allows for a clean and interactive documentation experience. ```properties # openapi.properties micronaut.openapi.views.spec=redoc.enabled=true, redoc.sort-props-alphabetically=true, redoc.hide-download-button=false ``` -------------------------------- ### Expose ReDoc as Static Resource Source: https://context7.com/micronaut-projects/micronaut-openapi/llms.txt Configure `application.yml` to expose the ReDoc view as a static resource. Access the ReDoc UI at the configured mapping path. ```yaml # application.yml micronaut: router: static-resources: swagger: paths: classpath:META-INF/swagger mapping: /swagger/** redoc: paths: classpath:META-INF/swagger/views/redoc mapping: /redoc/** ``` -------------------------------- ### Configure Endpoint Servers Source: https://github.com/micronaut-projects/micronaut-openapi/blob/7.0.x/src/main/docs/guide/endpoints/endpointservers.adoc Provide a JSON array of server definitions to the `endpoints.servers` property. This allows you to specify multiple servers with descriptions and variables for dynamic configuration. ```properties endpoints.servers=[ { "url": "https://{username}.gigantic-server.com:{port}/{basePath}", "description": "The production API server", "variables": { "username": { "default": "demo", "description": "this value is assigned by the service provider, in this example `gigantic-server.com`" }, "port": { "enum": [ "8443", "443" ], "default": "8443" }, "basePath": { "default": "v2" } } } ] ``` -------------------------------- ### Controller-Based Spec Generation with Javadoc Source: https://context7.com/micronaut-projects/micronaut-openapi/llms.txt Micronaut automatically extracts API details from controller annotations and Javadoc comments, eliminating the need for explicit Swagger annotations. This example shows how path, parameters, and response types are inferred. ```java import io.micronaut.http.MediaType; import io.micronaut.http.annotation.Controller; import io.micronaut.http.annotation.Get; import reactor.core.publisher.Mono; @Controller public class HelloController { /** * @param name The person's name * @return The greeting */ @Get(uri = "/hello/{name}", produces = MediaType.TEXT_PLAIN) public Mono index(String name) { return Mono.just("Hello " + name + "!"); } } ``` ```yaml paths: /hello/{name}: get: operationId: index parameters: - name: name in: path description: The person's name required: true schema: type: string responses: 200: description: The greeting content: text/plain: schema: type: string ``` -------------------------------- ### Create Micronaut App with OpenAPI Feature Source: https://github.com/micronaut-projects/micronaut-openapi/blob/7.0.x/src/main/docs/guide/cli.adoc Use the Micronaut CLI to create a new application and include the OpenAPI feature by specifying it in the `--features` flag. This sets up the project with essential OpenAPI configuration. ```commandline $ mn create-app my-openapi-app --features openapi ``` -------------------------------- ### Configure Micronaut Security for Token Validation Source: https://github.com/micronaut-projects/micronaut-openapi/blob/7.0.x/src/main/docs/guide/openApiViews/swaggerui/oauth2.adoc Configure Micronaut Security to enable JWT validation and specify the JWKS URL for token verification. This setup is crucial for validating tokens issued by your OAuth 2.0 authorization server. ```yaml micronaut: security: enabled: true token: jwt: enabled: true signatures: jwks: okta: url: 'https://mycompany.okta.com/oauth2/default/v1/keys' intercept-url-map: - pattern: /swagger-ui/** httpMethod: GET access: - isAnonymous() - pattern: /swagger/** access: - isAnonymous() router: static-resources: swagger: paths: classpath:META-INF/swagger mapping: /swagger/** swagger-ui: paths: classpath:META-INF/swagger/views/swagger-ui mapping: /swagger-ui/** ``` -------------------------------- ### Annotate Controller Methods with OpenAPIGroup Source: https://github.com/micronaut-projects/micronaut-openapi/blob/7.0.x/src/main/docs/guide/micronautOpenApiAnnotations/openApiGroup.adoc Use the @OpenAPIGroup annotation on controller methods to include or exclude them from specific OpenAPI groups. This example demonstrates excluding a method from 'v2', including a method in 'v2', and including a method in both 'v1' and 'v2'. ```java @Controller public class ApiController { @OpenAPIGroup(exclude = "v2") @Get("/read/{id}") public String read(String id) { return "OK!"; } @OpenAPIGroup("v2") @Post("/save/{id}") public String save2(String id, Object body) { return "OK!"; } @OpenAPIGroup({"v1", "v2"}) @Post("/save") public String save(Object body) { return "OK!"; } } ``` -------------------------------- ### Configure Custom Schema Mappings via System Properties Source: https://github.com/micronaut-projects/micronaut-openapi/blob/7.0.x/src/main/docs/guide/customSerializers.adoc Alternatively, set custom schema mappings using system properties. This approach is equivalent to using the `application.yml` configuration. ```bash -Dmicronaut.openapi.schema.org.somepackage.MyComplexType=java.lang.String -Dmicronaut.openapi.schema.org.somepackage.MyComplexType2=java.lang.Integer ``` -------------------------------- ### Enable RapiDoc View Source: https://context7.com/micronaut-projects/micronaut-openapi/llms.txt Configuration to enable the RapiDoc view for OpenAPI documentation with custom styling and sorting. ```APIDOC ## Configuration: openapi.properties ### Description Enables RapiDoc with custom background and text colors, and endpoint sorting. ```properties micronaut.openapi.views.spec=rapidoc.enabled=true, rapidoc.bg-color=#14191f, rapidoc.text-color=#aec2e0, rapidoc.sort-endpoints-by=method, rapidoc.render-style=read ``` ## Configuration: application.yml ### Description Exposes RapiDoc at `/rapidoc/**`. ```yaml micronaut: router: static-resources: rapidoc: paths: classpath:META-INF/swagger/views/rapidoc mapping: /rapidoc/** ``` ``` -------------------------------- ### Customizing Operation IDs with @OpenAPIDecorator Source: https://github.com/micronaut-projects/micronaut-openapi/blob/7.0.x/src/main/docs/guide/micronautOpenApiAnnotations/openApiDecorator.adoc Use @OpenAPIDecorator to add prefixes and suffixes to operation IDs, preventing conflicts between controllers with similar operation names. This example shows how to apply different prefixes and suffixes to operations in separate controller interfaces. ```java @OpenAPIDecorator(opIdPrefix = "cats-", opIdSuffix = "-suffix") @Controller("/cats") interface MyCatsOperations extends Api { } @OpenAPIDecorator("dogs-") @Controller("/dogs") interface MyDogsOperations extends Api { } ``` -------------------------------- ### Expose RapiDoc as Static Resource Source: https://context7.com/micronaut-projects/micronaut-openapi/llms.txt Configure `application.yml` to expose the RapiDoc view as a static resource. Access the RapiDoc UI at the configured mapping path. ```yaml # application.yml micronaut: router: static-resources: swagger: paths: classpath:META-INF/swagger mapping: /swagger/** rapidoc: paths: classpath:META-INF/swagger/views/rapidoc mapping: /rapidoc/** ``` -------------------------------- ### Initialize Scalar API Reference Source: https://github.com/micronaut-projects/micronaut-openapi/blob/7.0.x/openapi/src/main/resources/templates/scalar/index.html This script initializes the Scalar API reference component. It dynamically loads the Scalar JavaScript file and then creates the API reference instance, configuring it with sources and attributes. Ensure the script is executed after the DOM is ready. ```javascript const extract = function(v) { return decodeURIComponent(v.replace(/(?:^|.\*;\s extit{contextPath}\s extit{=}\s extit{([^;]*)). extit{$|^. extit{$}}, "$1")); }; const cookie = extract(document.cookie); contextPath = cookie === '' ? extract(window.location.search.substring(1)) : cookie; if (!isSafeContextPath(contextPath)) { contextPath = ''; } const head = document.getElementsByTagName("head")[0]; window.onload = function() { const apiReferenceScript = script(contextPath + "{{scalar.js.url.prefix}}standalone.js", head); apiReferenceScript.onload = function() { Scalar.createApiReference('#app', { {{scalar.sources}} {{scalar.attributes}} }); } } function script(src, head) { const el = document.createElement("script"); el.src = src; head.appendChild(el); return el; } function isSafeContextPath(cp) { if (typeof cp !== 'string') return false; cp = cp.trim(); if (cp === '') return true; // allow empty = root try { // Build against current origin to normalize const u = new URL(cp, window.location.origin); // Must be same origin and http(s) if (u.origin !== window.location.origin) return false; if (!(u.protocol === 'http:' || u.protocol === 'https:')) return false; // Path only: no query or fragment if (u.search !== '' || u.hash !== '') return false; const p = u.pathname; // Must start with a single slash and contain only safe path chars if (!p.startsWith('/')) return false; if (!/^\/[A-Za-z0-9.\_~\-\/]*.test(p)) return false; // Disallow protocol relative indicators traversal and HTML breaking chars if (p.includes('//') || p.includes('..')) return false; if (/[\[<> ``` -------------------------------- ### Define Sample Properties for Placeholders Source: https://github.com/micronaut-projects/micronaut-openapi/blob/7.0.x/src/main/docs/guide/configuration/applicationConfiguration.adoc Define sample properties in application.yml that can be used as placeholders in OpenAPI annotations. ```yaml my: api: version: 1.0.0 title: My title api-description: My description ``` -------------------------------- ### Configure Static Resources for Swagger YAML and UI Source: https://github.com/micronaut-projects/micronaut-openapi/blob/7.0.x/src/main/docs/guide/openApiViews/swaggerui.adoc Expose the generated OpenAPI YAML files and Swagger UI views by configuring static resource handlers in `application.yml`. ```yaml micronaut: router: static-resources: swagger: paths: classpath:META-INF/swagger mapping: /swagger/** swagger-ui: paths: classpath:META-INF/swagger/views/swagger-ui mapping: /swagger-ui/** ``` -------------------------------- ### Enable All OpenAPI Views Together Source: https://context7.com/micronaut-projects/micronaut-openapi/llms.txt Configuration to enable multiple OpenAPI views simultaneously. ```APIDOC ## Configuration: openapi.properties ### Description Enables Swagger UI, ReDoc, OpenAPI Explorer, Scalar, and RapiDoc with custom RapiDoc styling. ```properties micronaut.openapi.views.spec=swagger-ui.enabled=true, redoc.enabled=true, openapi-explorer.enabled=true, scalar.enabled=true, rapidoc.enabled=true, rapidoc.bg-color=#14191f, rapidoc.text-color=#aec2e0 ``` ``` -------------------------------- ### Exposing OpenAPI YAML at Runtime Source: https://context7.com/micronaut-projects/micronaut-openapi/llms.txt Configuration to serve the generated OpenAPI specification YAML file as a static resource. ```APIDOC ## Configuration: application.yml ### Description Exposes the OpenAPI YAML at `/swagger/**`. ```yaml micronaut: router: static-resources: swagger: paths: classpath:META-INF/swagger mapping: /swagger/** ``` Access the spec at: `http://localhost:8080/swagger/hello-world-1.0.yml` ``` -------------------------------- ### Expose OpenAPI YAML at Runtime Source: https://context7.com/micronaut-projects/micronaut-openapi/llms.txt Configure `application.yml` to serve the generated OpenAPI spec file as a static resource. Access the spec at the configured mapping path. ```yaml # src/main/resources/application.yml micronaut: router: static-resources: swagger: paths: classpath:META-INF/swagger mapping: /swagger/** ``` -------------------------------- ### Configure OpenAPI Views in Gradle (Kotlin) Source: https://github.com/micronaut-projects/micronaut-openapi/blob/7.0.x/src/main/docs/guide/openApiViews/viewsGenerationWithSystemProperties.adoc Configure the `micronaut.openapi.views.spec` system property for Gradle Kotlin projects using `JAVA_TOOL_OPTIONS`. ```shell JAVA_TOOL_OPTIONS=-Dmicronaut.openapi.views.spec=redoc.enabled=true,rapidoc.enabled=true,openapi-explorer.enabled=true,swagger-ui.enabled=true,swagger-ui.theme=flattop \ ./gradlew --no-daemon clean assemble ``` -------------------------------- ### Configure OpenAPI Target and Naming Strategy Source: https://github.com/micronaut-projects/micronaut-openapi/blob/7.0.x/src/main/docs/guide/configuration/applicationConfiguration.adoc Use application.yml to specify the output file for the OpenAPI specification and set the property naming strategy. ```yaml micronaut: openapi: target: file: myspecfile.yml property: naming: strategy: KEBAB_CASE ``` -------------------------------- ### Configure Project Directory with KSP Source: https://github.com/micronaut-projects/micronaut-openapi/blob/7.0.x/src/main/docs/guide/kotlin.adoc Set the project directory for the annotation processor when using KSP in Gradle. This is recommended to avoid dummy file creation and ensure proper functionality. ```groovy ksp { arg("micronaut.openapi.project.dir", projectDir.toString()) } ``` -------------------------------- ### Enable Swagger UI View Source: https://context7.com/micronaut-projects/micronaut-openapi/llms.txt Configuration to enable and customize the Swagger UI view for OpenAPI documentation. ```APIDOC ## Configuration: openapi.properties ### Description Enables Swagger UI with custom themes and settings. ```properties micronaut.openapi.views.spec=swagger-ui.enabled=true, swagger-ui.theme=flattop, swagger-ui.deepLinking=true, swagger-ui.displayRequestDuration=true, swagger-ui.operationsSorter=method ``` ## Configuration: application.yml ### Description Exposes Swagger UI at `/swagger-ui/**`. ```yaml micronaut: router: static-resources: swagger-ui: paths: classpath:META-INF/swagger/views/swagger-ui mapping: /swagger-ui/** ``` Access Swagger UI at: `http://localhost:8080/swagger-ui` ``` -------------------------------- ### Expose Swagger UI as Static Resource Source: https://context7.com/micronaut-projects/micronaut-openapi/llms.txt Configure `application.yml` to expose the Swagger UI as a static resource. Access the UI at the configured mapping path. ```yaml # application.yml – expose swagger YAML and UI as static resources micronaut: router: static-resources: swagger: paths: classpath:META-INF/swagger mapping: /swagger/** swagger-ui: paths: classpath:META-INF/swagger/views/swagger-ui mapping: /swagger-ui/** ``` -------------------------------- ### Enable OpenAPI 3.1 Support Source: https://context7.com/micronaut-projects/micronaut-openapi/llms.txt Enable the OpenAPI 3.1.0 format and specify the JSON Schema dialect. This is configured in a properties file. ```properties micronaut.openapi.openapi31.enabled=true micronaut.openapi.openapi31.json-schema-dialect=https://json-schema.org/draft/2020-12/schema ``` -------------------------------- ### Configure OpenAPI Views in build.gradle (Kotlin) Source: https://github.com/micronaut-projects/micronaut-openapi/blob/7.0.x/src/main/docs/guide/openApiViews/viewsGenerationWithSystemProperties.adoc Configure the `micronaut.openapi.views.spec` system property within the `build.gradle` file for Kotlin projects using `kapt` arguments. ```kotlin kapt { arguments { arg("micronaut.openapi.views.spec", "redoc.enabled=true,rapidoc.enabled=true,openapi-explorer.enabled=true,swagger-ui.enabled=true,swagger-ui.theme=flattop") } } ``` -------------------------------- ### Enable Swagger UI View Source: https://context7.com/micronaut-projects/micronaut-openapi/llms.txt Enable Swagger UI view generation by setting properties in `openapi.properties`. Views are generated to `META-INF/swagger/views/swagger-ui` at compile time. ```properties # openapi.properties micronaut.openapi.views.spec=swagger-ui.enabled=true, swagger-ui.theme=flattop, swagger-ui.deepLinking=true, swagger-ui.displayRequestDuration=true, swagger-ui.operationsSorter=method ``` -------------------------------- ### Generate Client and Server Code with Gradle Source: https://context7.com/micronaut-projects/micronaut-openapi/llms.txt Use the Micronaut Gradle Plugin to generate client and server code from OpenAPI specifications. Specify input spec files and output package names for APIs and models. ```kotlin plugins { id("io.micronaut.openapi") version "..." } micronaut { openapi { client(file("src/main/resources/petstore.yml")) { apiPackageName.set("io.example.client.api") modelPackageName.set("io.example.client.model") } server(file("src/main/resources/api.yml")) { apiPackageName.set("io.example.server.api") modelPackageName.set("io.example.server.model") } } } ``` -------------------------------- ### Enable Multiple OpenAPI Views Simultaneously Source: https://context7.com/micronaut-projects/micronaut-openapi/llms.txt Configure OpenAPI properties to enable multiple documentation views concurrently. This allows users to choose their preferred view. ```properties # openapi.properties micronaut.openapi.views.spec=swagger-ui.enabled=true, redoc.enabled=true, openapi-explorer.enabled=true, scalar.enabled=true, rapidoc.enabled=true, rapidoc.bg-color=#14191f, rapidoc.text-color=#aec2e0 ``` -------------------------------- ### Maven POM Configuration for Java Source: https://github.com/micronaut-projects/micronaut-openapi/blob/7.0.x/src/main/docs/guide/spring/springWithMaven.adoc Add these dependencies and build plugin configurations to your pom.xml for Java projects. ```xml io.micronaut.openapi micronaut-openapi-annotations ${micronaut.openapi.version} provided org.apache.maven.plugins maven-compiler-plugin io.micronaut.spring micronaut-spring-web-annotation ${micronaut.spring.version} io.micronaut.spring micronaut-spring-boot-annotation ${micronaut.spring.version} io.micronaut micronaut-inject-java ${micronaut.core.version} io.micronaut.openapi micronaut-openapi ${micronaut.openapi.version} ``` -------------------------------- ### Spring / Spring Boot Integration Source: https://context7.com/micronaut-projects/micronaut-openapi/llms.txt Instructions for using Micronaut OpenAPI as a drop-in replacement for springdoc-openapi or springfox in Spring Boot applications. ```APIDOC ## Spring / Spring Boot Integration Use `micronaut-openapi` as a drop-in replacement for springdoc-openapi or springfox in Spring Boot applications: ```kotlin // build.gradle.kts dependencies { annotationProcessor("io.micronaut.spring:micronaut-spring-web-annotation:$micronautSpringVersion") annotationProcessor("io.micronaut.spring:micronaut-spring-boot-annotation:$micronautSpringVersion") annotationProcessor("io.micronaut:micronaut-inject-java:$micronautCoreVersion") annotationProcessor("io.micronaut.openapi:micronaut-openapi:$micronautOpenapiVersion") compileOnly("io.micronaut.openapi:micronaut-openapi-annotations:$micronautOpenapiVersion") } // Remove Micronaut-generated metadata from the final Spring Boot jar tasks.register("removeMnFiles") { doLast { delete(layout.buildDirectory.file("/classes/java/main/META-INF/micronaut")) delete( layout.buildDirectory.dir("/classes/java/main").get().asFileTree.matching { include("**/*\$Definition*.class", "**/*\$Intercepted*.class", "**/*\$Introspection*.class") }.files ) } dependsOn(tasks.named("classes")) } tasks.jar { dependsOn(tasks.named("removeMnFiles")) } ``` ``` -------------------------------- ### Application Configuration for Versioning Source: https://github.com/micronaut-projects/micronaut-openapi/blob/7.0.x/src/main/docs/guide/versionsAndGroups/versions.adoc Configuration in application.yml to enable and customize API versioning, specifically enabling version parameters. ```APIDOC ## application.yml This configuration enables Micronaut's router versioning and specifically enables version parameters with the name 'version'. ``` -------------------------------- ### Configure Endpoint Class and Metadata Source: https://github.com/micronaut-projects/micronaut-openapi/blob/7.0.x/src/main/docs/guide/endpoints/micronautendpoints.adoc Customize endpoint behavior by specifying its class and optionally adding tags, servers, and security requirements in the `openapi.properties` file. ```properties endpoints.refresh.class=io.micronaut.management.endpoint.refresh.RefreshEndpoint endpoints.refresh.servers=[{"url": "https://staging.gigantic-server.com/v1", "description": "Staging server"}] endpoints.refresh.security-requirements=[{"petstore_auth": ["write:pets", "read:pets"]}] ``` -------------------------------- ### Configure OpenAPI Views in Maven (Java) Source: https://github.com/micronaut-projects/micronaut-openapi/blob/7.0.x/src/main/docs/guide/openApiViews/viewsGenerationWithSystemProperties.adoc Configure the `micronaut.openapi.views.spec` system property for Maven Java projects using the `maven-compiler-plugin`. ```xml org.apache.maven.plugins maven-compiler-plugin true -Amicronaut.openapi.views.spec=rapidoc.enabled=true,openapi-explorer.enabled=true,swagger-ui.enabled=true,swagger-ui.theme=flattop ... ``` -------------------------------- ### Configure System Property in gradle.properties Source: https://github.com/micronaut-projects/micronaut-openapi/blob/7.0.x/src/main/docs/guide/configuration/systemPropertyConfiguration.adoc Define system properties for OpenAPI processing in the gradle.properties file for project-wide settings. ```properties org.gradle.jvmargs=-Dmicronaut.openapi.property.naming.strategy=SNAKE_CASE ``` -------------------------------- ### Enable Asciidoc Generation Source: https://github.com/micronaut-projects/micronaut-openapi/blob/7.0.x/src/main/docs/guide/convertToAdoc.adoc To enable Asciidoc generation, set the system property -Dmicronaut.openapi.adoc.enabled=true and add the micronaut-openapi-adoc dependency to your classpath. ```groovy annotationProcessor("io.micronaut.openapi:micronaut-openapi-adoc") ``` -------------------------------- ### Configure Java Compiler for Parameter Names (Gradle) Source: https://github.com/micronaut-projects/micronaut-openapi/blob/7.0.x/src/main/docs/guide/gettingStarted.adoc Ensure correct parameter names for annotation processor operation by compiling with the -parameters flag. This is recommended for all libraries from which you plan to add controllers. ```groovy tasks.withType(JavaCompile).configureEach { options.compilerArgs = [ '-parameters' ] } ```