springdoc.swagger-ui.supportedSubmitMethods="get", "put", "post", "delete", "options", "head", "patch", "trace"+
springdoc.swagger-ui.supportedSubmitMethods=get, put, post, delete, options, head, patch, trace
diff --git a/docs/core-properties.html b/docs/core-properties.html index 93f8718..b5577ab 100644 --- a/docs/core-properties.html +++ b/docs/core-properties.html @@ -56,37 +56,37 @@
springdoc.packages-to-scan
*
List of Strings
.The list of packages to scan (comma separated)
List of Strings
. The list of packages to scan (comma separated)
springdoc.paths-to-match
/*
List of Strings
.The list of paths to match (comma separated)
List of Strings
. The list of paths to match (comma separated)
springdoc.produces-to-match
/*
List of Strings
.The list of produces mediaTypes to match (comma separated)
List of Strings
. The list of produces mediaTypes to match (comma separated)
springdoc.headers-to-match
/*
List of Strings
.The list of headers to match (comma separated)
List of Strings
. The list of headers to match (comma separated)
springdoc.consumes-to-match
/*
List of Strings
.The list of consumes mediaTypes to match (comma separated)
List of Strings
. The list of consumes mediaTypes to match (comma separated)
springdoc.paths-to-exclude
List of Strings
.The list of paths to exclude (comma separated)
List of Strings
. The list of paths to exclude (comma separated)
springdoc.packages-to-exclude
List of Strings
.The list of packages to exclude (comma separated)
List of Strings
. The list of packages to exclude (comma separated)
springdoc.default-consumes-media-type
springdoc.default-produces-media-type
/
String
.The default produces media type.
String
. The default produces media type.
springdoc.cache.disabled
Boolean
. When true, automatically adds @ControllerAdvice responses to all the generated responses.
springdoc.api-docs.groups.enabled
true
Boolean
. To disable the springdoc-openapi groups.
springdoc.group-configs[0].group
String
.The group name
String
. The group name
springdoc.group-configs[0].display-name
String
.The display name of the group.
String
. The display name of the group.
springdoc.group-configs[0].packages-to-scan
*
List of Strings
.The list of packages to scan for a group (comma separated)
List of Strings
. The list of packages to scan for a group (comma separated)
springdoc.group-configs[0].paths-to-match
/*
List of Strings
.The list of paths to match for a group(comma separated)
List of Strings
. The list of paths to match for a group (comma separated)
springdoc.group-configs[0].paths-to-exclude
``
List of Strings
.The list of paths to exclude for a group(comma separated)
List of Strings
. The list of paths to exclude for a group (comma separated)
springdoc.group-configs[0].packages-to-exclude
List of Strings
.The list of packages to exclude for a group(comma separated)
List of Strings
. The list of packages to exclude for a group (comma separated)
springdoc.group-configs[0].produces-to-match
/*
List of Strings
.The list of produces mediaTypes to match (comma separated)
List of Strings
. The list of produces mediaTypes to match (comma separated)
springdoc.group-configs[0].consumes-to-match
/*
List of Strings
.The list of consumes mediaTypes to match (comma separated)
List of Strings
. The list of consumes mediaTypes to match (comma separated)
springdoc.group-configs[0].headers-to-match
/*
List of Strings
.The list of headers to match (comma separated)
List of Strings
. The list of headers to match (comma separated)
springdoc.webjars.prefix
/webjars
String
, To change the webjars prefix that is visible the URL of swagger-ui for spring-webflux.
String
. To change the webjars prefix that is visible the URL of swagger-ui for spring-webflux.
springdoc.api-docs.resolve-schema-properties
Boolean
. To make spring security login-endpoint visible.
springdoc.pre-loading-enabled
false
Boolean
. Pre-loading setting to load OpenAPI on application startup.
springdoc.pre-loading-locales
List of Strings
.The list of locales to load OpenAPI on application startup.(comma separated) If not specified, it will preload with the default Locale.
List of Strings
. The list of locales to load OpenAPI on application startup (comma separated). If not specified, it will preload with the default Locale.
springdoc.writer-with-order-by-keys
springdoc.enable-kotlin
true
Boolproperty resolver on @Schema (extensionean
. To enable Kotlin support.
Boolean
. To enable Kotlin support.
springdoc.enable-hateoas
springdoc.api-docs.version
openapi_3_0
String
. To Choose OpenAPI 3.0
or OpenAPI 3.1
(using the value OPENAPI_3_1
).
openapi_3_1
String
. To choose OpenAPI 3.0
or OpenAPI 3.1
(using the value OPENAPI_3_1
).
springdoc.default-flat-param-object
false
Boolean
. Adjust indentation when parsing the @Operation
annotation in Kotlin.
springdoc.allowed-locales
List of Strings
. The list of allowed locales for OpenAPI (comma separated, for example US,fr-CA
).
springdoc.enable-extra-schemas
true
Boolean
. To enable default support for extra Schemas, from java.time
package like LocalTime
, Duration
, but also other Java classes like java.util.Locale
or java.nio.charset.Charset
springdoc.explicit-object-schema
false
Boolean
. Set explicit-object-schema to true
to always include type: object
in the schema, or to false
to omit type: object
.
springdoc.use-arbitrary-schemas
false
Boolean
. When set to true
, schemas without a defined type will be deserialized as an ArbitrarySchema
(with no type), instead of an ObjectSchema
with type: object
.
Demo Spring Boot 3 WebFlux with Functional endpoints OpenAPI 3
springdoc.swagger-ui.supportedSubmitMethods="get", "put", "post", "delete", "options", "head", "patch", "trace"+
springdoc.swagger-ui.supportedSubmitMethods=get, put, post, delete, options, head, patch, trace
---
-@Bean
+@Bean
@Primary
fun swaggerUiConfig(config: SwaggerUiConfigProperties): SwaggerUiConfigProperties {
config.showCommonExtensions = true
config.queryConfigEnabled = true
return config
}
----
If you need to manually adjust the URL displayed in the Swagger UI, implement the ServerBaseUrlCustomizer
interface. This might be necessary to remove the port number, for example.
@Bean
+public class CustomServerBaseUrlCustomizer implements ServerBaseUrlCustomizer {
+ @Override
+ public String customize(String serverBaseUrl) {
+ try {
+ URL url = new URL(serverBaseUrl);
+ if (url.getHost().contains(".com")) {
+ serverBaseUrl = new URL(url.getProtocol(),url.getHost(),url.getFile()).toString();
+ }
+ } catch (MalformedURLException ex) {
+ // nothing we can do
+ }
+
+ return serverBaseUrl;
+ }
+}
+
+@JsonView
annotations in Spring MVC APIs supported?@PostMapping(value = "/upload", consumes = {MediaType.MULTIPART_FORM_DATA_VALUE})
+public ResponseEntity<?> upload(@Parameter(description = "file") final MultipartFile file) {
+ return null;
+}
+
+@PostMapping(value = "/uploadFileWithQuery", consumes = {MediaType.MULTIPART_FORM_DATA_VALUE})
+public ResponseEntity<?> uploadFileWithQuery(@Parameter(description = "file") @RequestPart("file") final MultipartFile file,
+ @Parameter(description = "An extra query parameter") @RequestParam String name) {
+ return null;
+}
+
+@PostMapping(value = "/uploadFileWithJson", consumes = {MediaType.MULTIPART_FORM_DATA_VALUE}, produces = {
+ MediaType.APPLICATION_JSON_VALUE})
+public ResponseEntity<?> uploadFileWithJson(
+ @RequestBody(content = @Content(encoding = @Encoding(name = "jsonRequest", contentType = MediaType.APPLICATION_JSON_VALUE)))
+ @Parameter(description = "An extra JSON payload sent with file") @RequestPart("jsonRequest") final JsonRequest jsonRequest,
+ @RequestPart("file") final MultipartFile file) {
+ return null;
+}
+
+springdoc-openapi
SNAPSHOT
To achieve that, you can on your pom.xml or your settings.xml the following section:
+To achieve that, configure your pom.xml file with the following <repositories>
section:
<repositories>
- <repository>
- <id>snapshots-repo</id>
- <url>https://s01.oss.sonatype.org/content/repositories/snapshots</url>
- <releases><enabled>false</enabled></releases>
- <snapshots><enabled>true</enabled></snapshots>
- </repository>
- </repositories>
+ <repositories>
+ <repository>
+ <name>Central Portal Snapshots</name>
+ <id>central-portal-snapshots</id>
+ <url>https://central.sonatype.com/repository/maven-snapshots/</url>
+ <releases>
+ <enabled>false</enabled>
+ </releases>
+ <snapshots>
+ <enabled>true</enabled>
+ </snapshots>
+ </repository>
+ </repositories>
https://github.com/swagger-api/swagger-ui/blob/master/docs/usage/configuration.md#requestinterceptor
+https://github.com/swagger-api/swagger-ui/blob/main/docs/usage/configuration.md#requestinterceptor
When your application is using spring without (spring-boot), you need to add beans and auto-configuration that are natively provided in spring-boot.
+For example, lets assume you want load the swagger-ui in spring-mvc application:
+You mainly, need to add the springdoc-openapi module
+<dependency>
+ <groupId>org.springdoc</groupId>
+ <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
+ <version>last.version</version>
+</dependency>
+If you don’t have the spring-boot and spring-boot-autoconfigure dependencies, you need to add them. And pay attention to the compatibility matrix, between you spring.version and spring-boot.version. For example, in this case (spring.version=5.1.12.RELEASE):
+ <dependency>
+ <groupId>org.springframework.boot</groupId>
+ <artifactId>spring-boot-autoconfigure</artifactId>
+ <version>3.3.3</version>
+ </dependency>
+Scan for the springdoc-openapi
'auto-configuration classes that spring-boot automatically loads for you.
Depending on your module, you can find them on the file: spring.factories
of each springdoc-openapi
module.
@Configuration
+@EnableWebMvc
+public class WebConfig implements WebApplicationInitializer {
+
+ @Override
+ public void onStartup(ServletContext servletContext) {
+ WebApplicationContext context = getContext();
+ servletContext.addListener(new ContextLoaderListener(context));
+ ServletRegistration.Dynamic dispatcher = servletContext.addServlet("RestServlet",
+ new DispatcherServlet(context));
+ dispatcher.setLoadOnStartup(1);
+ dispatcher.addMapping("/*");
+ }
+
+ private AnnotationConfigWebApplicationContext getContext() {
+ AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
+ context.register(this.getClass(),
+ SpringDocConfiguration.class,
+ SpringDocConfigProperties.class,
+ SpringDocSpecPropertiesConfiguration.class,
+ SpringDocWebMvcConfiguration.class,
+ MultipleOpenApiSupportConfiguration.class,
+ SwaggerConfig.class,
+ SwaggerUiConfigProperties.class,
+ SwaggerUiOAuthProperties.class,
+ );
+ return context;
+ }
+}
+
+Depending on your module, you can find them on the file: org.springframework.boot.autoconfigure.AutoConfiguration.imports
of each springdoc-openapi
module.
For groups usage make sure your GroupedOpenApi
Beans are scanned.
If additionally, you are using custom context path
: /my-servlet-path
. Make sure you declare the following property:
spring.mvc.servlet.path=/my-servlet-path+
springdoc-openapi
with spring-boot
?springdoc-openapi 2.x
is compatible with spring-boot 3
.
In general, you should only pick the last stable version as per today 2.6.0.
+In general, you should only pick the last stable version as per today 2.8.11.
More precisely, this the exhaustive list of spring-boot versions against which springdoc-openapi
has been built:
Spring Boot Versions
Springdoc OpenAPI Versions
3.5.x
2.8.x
3.4.x
2.7.x
- 2.8.x
3.3.x
2.6.x
3.2.x
2.3.x
- 2.5.x
3.1.x
2.2.x
3.0.x
2.0.x
+
2.0.x
- 2.1.x
2.7.x
, 1.5.x
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
- <version>2.6.0</version>
+ <version>2.8.11</version>
</dependency>
@@ -69,7 +69,7 @@ Documentation can be available in yaml format as well, on the following path : /v3/api-docs.yaml
+Documentation will be available in yaml format as well, on the following path : /v3/api-docs.yaml
Starting from version v2.8.7
, springdoc-openapi
provides a BOM (Bill of Materials) to manage the dependencies of the project.
+You can declare it in your project as follows:
<dependencyManagement>
+ <dependencies>
+ <dependency>
+ <groupId>org.springdoc</groupId>
+ <artifactId>springdoc-openapi-bom</artifactId>
+ <version>2.8.11</version>
+ <type>pom</type>
+ <scope>import</scope>
+ </dependency>
+ </dependencies>
+ </dependencyManagement>
+springdoc-openapi
relies on standard spring configuration properties (yml or properties) using the standard files locations.
springdoc-openapi
relies on standard spring configuration properties (yml or properties) using the standard files locations.
springdoc.packages-to-scan
*
List of Strings
.The list of packages to scan (comma separated)
List of Strings
. The list of packages to scan (comma separated)
springdoc.paths-to-match
/*
List of Strings
.The list of paths to match (comma separated)
List of Strings
. The list of paths to match (comma separated)
springdoc.produces-to-match
/*
List of Strings
.The list of produces mediaTypes to match (comma separated)
List of Strings
. The list of produces mediaTypes to match (comma separated)
springdoc.headers-to-match
/*
List of Strings
.The list of headers to match (comma separated)
List of Strings
. The list of headers to match (comma separated)
springdoc.consumes-to-match
/*
List of Strings
.The list of consumes mediaTypes to match (comma separated)
List of Strings
. The list of consumes mediaTypes to match (comma separated)
springdoc.paths-to-exclude
List of Strings
.The list of paths to exclude (comma separated)
List of Strings
. The list of paths to exclude (comma separated)
springdoc.packages-to-exclude
List of Strings
.The list of packages to exclude (comma separated)
List of Strings
. The list of packages to exclude (comma separated)
springdoc.default-consumes-media-type
springdoc.default-produces-media-type
/
String
.The default produces media type.
String
. The default produces media type.
springdoc.cache.disabled
Boolean
. When true, automatically adds @ControllerAdvice responses to all the generated responses.
springdoc.api-docs.groups.enabled
true
Boolean
. To disable the springdoc-openapi groups.
springdoc.group-configs[0].group
String
.The group name
String
. The group name
springdoc.group-configs[0].display-name
String
.The display name of the group.
String
. The display name of the group.
springdoc.group-configs[0].packages-to-scan
*
List of Strings
.The list of packages to scan for a group (comma separated)
List of Strings
. The list of packages to scan for a group (comma separated)
springdoc.group-configs[0].paths-to-match
/*
List of Strings
.The list of paths to match for a group(comma separated)
List of Strings
. The list of paths to match for a group (comma separated)
springdoc.group-configs[0].paths-to-exclude
``
List of Strings
.The list of paths to exclude for a group(comma separated)
List of Strings
. The list of paths to exclude for a group (comma separated)
springdoc.group-configs[0].packages-to-exclude
List of Strings
.The list of packages to exclude for a group(comma separated)
List of Strings
. The list of packages to exclude for a group (comma separated)
springdoc.group-configs[0].produces-to-match
/*
List of Strings
.The list of produces mediaTypes to match (comma separated)
List of Strings
. The list of produces mediaTypes to match (comma separated)
springdoc.group-configs[0].consumes-to-match
/*
List of Strings
.The list of consumes mediaTypes to match (comma separated)
List of Strings
. The list of consumes mediaTypes to match (comma separated)
springdoc.group-configs[0].headers-to-match
/*
List of Strings
.The list of headers to match (comma separated)
List of Strings
. The list of headers to match (comma separated)
springdoc.webjars.prefix
/webjars
String
, To change the webjars prefix that is visible the URL of swagger-ui for spring-webflux.
String
. To change the webjars prefix that is visible the URL of swagger-ui for spring-webflux.
springdoc.api-docs.resolve-schema-properties
Boolean
. To make spring security login-endpoint visible.
springdoc.pre-loading-enabled
false
Boolean
. Pre-loading setting to load OpenAPI on application startup.
springdoc.pre-loading-locales
List of Strings
.The list of locales to load OpenAPI on application startup.(comma separated) If not specified, it will preload with the default Locale.
List of Strings
. The list of locales to load OpenAPI on application startup (comma separated). If not specified, it will preload with the default Locale.
springdoc.writer-with-order-by-keys
springdoc.enable-kotlin
true
Boolproperty resolver on @Schema (extensionean
. To enable Kotlin support.
Boolean
. To enable Kotlin support.
springdoc.enable-hateoas
springdoc.api-docs.version
-openapi_3_0
String
. To Choose OpenAPI 3.0
or OpenAPI 3.1
(using the value OPENAPI_3_1
).
openapi_3_1
String
. To choose OpenAPI 3.0
or OpenAPI 3.1
(using the value OPENAPI_3_1
).
springdoc.default-flat-param-object
false
Boolean
. Adjust indentation when parsing the @Operation
annotation in Kotlin.
springdoc.allowed-locales
List of Strings
. The list of allowed locales for OpenAPI (comma separated, for example US,fr-CA
).
springdoc.enable-extra-schemas
true
Boolean
. To enable default support for extra Schemas, from java.time
package like LocalTime
, Duration
, but also other Java classes like java.util.Locale
or java.nio.charset.Charset
springdoc.explicit-object-schema
false
Boolean
. Set explicit-object-schema to true
to always include type: object
in the schema, or to false
to omit type: object
.
springdoc.use-arbitrary-schemas
false
Boolean
. When set to true
, schemas without a defined type will be deserialized as an ArbitrarySchema
(with no type), instead of an ObjectSchema
with type: object
.
springdoc.swagger-ui.validatorUrl
By default, Swagger UI attempts to validate specs against swagger.io’s online validator. You can use this parameter to set a different validator URL, for example for locally deployed validators Validator Badge. Setting it to either none
, 127.0.0.1
or localhost
will disable validation.
By default, Swagger UI does not validate specs. You can use this parameter to set a validator URL, for example for against swagger.io’s online validator.
springdoc.swagger-ui.tryItOutEnabled
springdoc.swagger-ui.supportedSubmitMethods
Array=["get", "put", "post", "delete", "options", "head", "patch", "trace"]
. List of HTTP methods that have the "Try it out" feature enabled. An empty array disables "Try it out" for all operations. This does not filter the operations from the display.
Array=[get, put, post, delete, options, head, patch, trace]
. List of HTTP methods that have the "Try it out" feature enabled. An empty array disables "Try it out" for all operations. This does not filter the operations from the display.
springdoc.swagger-ui.queryConfigEnabled
Demo Spring Boot 3 WebFlux with Functional endpoints OpenAPI 3
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
- <version>2.6.0</version>
+ <version>2.8.11</version>
</dependency>
https://s01.oss.sonatype.org/content/repositories/snapshots/org/springdoc/
+https://central.sonatype.com/service/rest/repository/browse/maven-snapshots/org/springdoc/
---
-@Bean
+@Bean
@Primary
fun swaggerUiConfig(config: SwaggerUiConfigProperties): SwaggerUiConfigProperties {
config.showCommonExtensions = true
config.queryConfigEnabled = true
return config
}
----
If you need to manually adjust the URL displayed in the Swagger UI, implement the ServerBaseUrlCustomizer
interface. This might be necessary to remove the port number, for example.
@Bean
+public class CustomServerBaseUrlCustomizer implements ServerBaseUrlCustomizer {
+ @Override
+ public String customize(String serverBaseUrl) {
+ try {
+ URL url = new URL(serverBaseUrl);
+ if (url.getHost().contains(".com")) {
+ serverBaseUrl = new URL(url.getProtocol(),url.getHost(),url.getFile()).toString();
+ }
+ } catch (MalformedURLException ex) {
+ // nothing we can do
+ }
+
+ return serverBaseUrl;
+ }
+}
+
+@JsonView
annotations in Spring MVC APIs supported?@PostMapping(value = "/upload", consumes = {MediaType.MULTIPART_FORM_DATA_VALUE})
+public ResponseEntity<?> upload(@Parameter(description = "file") final MultipartFile file) {
+ return null;
+}
+
+@PostMapping(value = "/uploadFileWithQuery", consumes = {MediaType.MULTIPART_FORM_DATA_VALUE})
+public ResponseEntity<?> uploadFileWithQuery(@Parameter(description = "file") @RequestPart("file") final MultipartFile file,
+ @Parameter(description = "An extra query parameter") @RequestParam String name) {
+ return null;
+}
+
+@PostMapping(value = "/uploadFileWithJson", consumes = {MediaType.MULTIPART_FORM_DATA_VALUE}, produces = {
+ MediaType.APPLICATION_JSON_VALUE})
+public ResponseEntity<?> uploadFileWithJson(
+ @RequestBody(content = @Content(encoding = @Encoding(name = "jsonRequest", contentType = MediaType.APPLICATION_JSON_VALUE)))
+ @Parameter(description = "An extra JSON payload sent with file") @RequestPart("jsonRequest") final JsonRequest jsonRequest,
+ @RequestPart("file") final MultipartFile file) {
+ return null;
+}
+
+springdoc-openapi
SNAPSHOT
To achieve that, you can on your pom.xml or your settings.xml the following section:
+To achieve that, configure your pom.xml file with the following <repositories>
section:
<repositories>
- <repository>
- <id>snapshots-repo</id>
- <url>https://s01.oss.sonatype.org/content/repositories/snapshots</url>
- <releases><enabled>false</enabled></releases>
- <snapshots><enabled>true</enabled></snapshots>
- </repository>
- </repositories>
+ <repositories>
+ <repository>
+ <name>Central Portal Snapshots</name>
+ <id>central-portal-snapshots</id>
+ <url>https://central.sonatype.com/repository/maven-snapshots/</url>
+ <releases>
+ <enabled>false</enabled>
+ </releases>
+ <snapshots>
+ <enabled>true</enabled>
+ </snapshots>
+ </repository>
+ </repositories>
https://github.com/swagger-api/swagger-ui/blob/master/docs/usage/configuration.md#requestinterceptor
+https://github.com/swagger-api/swagger-ui/blob/main/docs/usage/configuration.md#requestinterceptor
springdoc-openapi
with spring-boot
?When your application is using spring without (spring-boot), you need to add beans and auto-configuration that are natively provided in spring-boot.
+For example, lets assume you want load the swagger-ui in spring-mvc application:
+You mainly, need to add the springdoc-openapi module
+<dependency>
+ <groupId>org.springdoc</groupId>
+ <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
+ <version>last.version</version>
+</dependency>
+If you don’t have the spring-boot and spring-boot-autoconfigure dependencies, you need to add them. And pay attention to the compatibility matrix, between you spring.version and spring-boot.version. For example, in this case (spring.version=5.1.12.RELEASE):
+ <dependency>
+ <groupId>org.springframework.boot</groupId>
+ <artifactId>spring-boot-autoconfigure</artifactId>
+ <version>3.3.3</version>
+ </dependency>
+Scan for the springdoc-openapi
'auto-configuration classes that spring-boot automatically loads for you.
Depending on your module, you can find them on the file: spring.factories
of each springdoc-openapi
module.
@Configuration
+@EnableWebMvc
+public class WebConfig implements WebApplicationInitializer {
+
+ @Override
+ public void onStartup(ServletContext servletContext) {
+ WebApplicationContext context = getContext();
+ servletContext.addListener(new ContextLoaderListener(context));
+ ServletRegistration.Dynamic dispatcher = servletContext.addServlet("RestServlet",
+ new DispatcherServlet(context));
+ dispatcher.setLoadOnStartup(1);
+ dispatcher.addMapping("/*");
+ }
+
+ private AnnotationConfigWebApplicationContext getContext() {
+ AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
+ context.register(this.getClass(),
+ SpringDocConfiguration.class,
+ SpringDocConfigProperties.class,
+ SpringDocSpecPropertiesConfiguration.class,
+ SpringDocWebMvcConfiguration.class,
+ MultipleOpenApiSupportConfiguration.class,
+ SwaggerConfig.class,
+ SwaggerUiConfigProperties.class,
+ SwaggerUiOAuthProperties.class,
+ );
+ return context;
+ }
+}
+
+Depending on your module, you can find them on the file: org.springframework.boot.autoconfigure.AutoConfiguration.imports
of each springdoc-openapi
module.
For groups usage make sure your GroupedOpenApi
Beans are scanned.
If additionally, you are using custom context path
: /my-servlet-path
. Make sure you declare the following property:
spring.mvc.servlet.path=/my-servlet-path+
springdoc-openapi
with spring-boot
?springdoc-openapi 2.x
is compatible with spring-boot 3
.
In general, you should only pick the last stable version as per today 2.6.0.
+In general, you should only pick the last stable version as per today 2.8.11.
More precisely, this the exhaustive list of spring-boot versions against which springdoc-openapi
has been built:
Spring Boot Versions
Springdoc OpenAPI Versions
3.5.x
2.8.x
3.4.x
2.7.x
- 2.8.x
3.3.x
2.6.x
3.2.x
2.3.x
- 2.5.x
3.1.x
2.2.x
3.0.x
2.0.x
+
2.0.x
- 2.1.x
2.7.x
, 1.5.x
Swagger UI unable to render definition
, when overriding the default spring registered HttpMessageConverter
?Swagger UI unable to render definition
, when overriding the default spring registered HttpMessageConverter
?When overriding the default spring-boot registered HttpMessageConverter
, you should have ByteArrayHttpMessageConverter
registered as well to have proper springdoc-openapi
support.
The issue is caused by the changes introduced by Spring-Boot 3.2.0 in particular for the Parameter Name Discovery. @@ -4573,65 +4702,15 @@
This is a community-based project, not maintained by the Spring Framework Contributors (Pivotal).
- - - - diff --git a/docs/migrating-from-springdoc-v1.html b/docs/migrating-from-springdoc-v1.html index 3cb50b0..22e713c 100644 --- a/docs/migrating-from-springdoc-v1.html +++ b/docs/migrating-from-springdoc-v1.html @@ -217,24 +217,12 @@ <dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
- <version>2.6.0</version>
+ <version>2.8.11</version>
</dependency>
@@ -71,7 +71,7 @@ <dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-starter-webmvc-api</artifactId>
- <version>2.6.0</version>
+ <version>2.8.11</version>
</dependency>
@@ -113,7 +113,7 @@ Documentation can be available in yaml format as well, on the following path : /v3/api-docs.yaml
+Documentation will be available in yaml format as well, on the following path : /v3/api-docs.yaml
Add the library to the list of your project dependencies (No additional configuration is needed)
@@ -125,7 +125,7 @@ <dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-starter-webflux-api</artifactId>
- <version>2.6.0</version>
+ <version>2.8.11</version>
</dependency>
@@ -450,7 +450,7 @@ Starting from version v2.8.7
, springdoc-openapi
provides a BOM (Bill of Materials) to manage the dependencies of the project.
+You can declare it in your project as follows:
<dependencyManagement>
+ <dependencies>
+ <dependency>
+ <groupId>org.springdoc</groupId>
+ <artifactId>springdoc-openapi-bom</artifactId>
+ <version>2.8.11</version>
+ <type>pom</type>
+ <scope>import</scope>
+ </dependency>
+ </dependencies>
+ </dependencyManagement>
+https://s01.oss.sonatype.org/content/repositories/snapshots/org/springdoc/
+https://central.sonatype.com/service/rest/repository/browse/maven-snapshots/org/springdoc/
springdoc-openapi
relies on standard spring configuration properties (yml or properties) using the standard files locations.
springdoc-openapi
relies on standard spring configuration properties (yml or properties) using the standard files locations.
springdoc.packages-to-scan
*
List of Strings
.The list of packages to scan (comma separated)
List of Strings
. The list of packages to scan (comma separated)
springdoc.paths-to-match
/*
List of Strings
.The list of paths to match (comma separated)
List of Strings
. The list of paths to match (comma separated)
springdoc.produces-to-match
/*
List of Strings
.The list of produces mediaTypes to match (comma separated)
List of Strings
. The list of produces mediaTypes to match (comma separated)
springdoc.headers-to-match
/*
List of Strings
.The list of headers to match (comma separated)
List of Strings
. The list of headers to match (comma separated)
springdoc.consumes-to-match
/*
List of Strings
.The list of consumes mediaTypes to match (comma separated)
List of Strings
. The list of consumes mediaTypes to match (comma separated)
springdoc.paths-to-exclude
List of Strings
.The list of paths to exclude (comma separated)
List of Strings
. The list of paths to exclude (comma separated)
springdoc.packages-to-exclude
List of Strings
.The list of packages to exclude (comma separated)
List of Strings
. The list of packages to exclude (comma separated)
springdoc.default-consumes-media-type
springdoc.default-produces-media-type
/
String
.The default produces media type.
String
. The default produces media type.
springdoc.cache.disabled
Boolean
. When true, automatically adds @ControllerAdvice responses to all the generated responses.
springdoc.api-docs.groups.enabled
true
Boolean
. To disable the springdoc-openapi groups.
springdoc.group-configs[0].group
String
.The group name
String
. The group name
springdoc.group-configs[0].display-name
String
.The display name of the group.
String
. The display name of the group.
springdoc.group-configs[0].packages-to-scan
*
List of Strings
.The list of packages to scan for a group (comma separated)
List of Strings
. The list of packages to scan for a group (comma separated)
springdoc.group-configs[0].paths-to-match
/*
List of Strings
.The list of paths to match for a group(comma separated)
List of Strings
. The list of paths to match for a group (comma separated)
springdoc.group-configs[0].paths-to-exclude
``
List of Strings
.The list of paths to exclude for a group(comma separated)
List of Strings
. The list of paths to exclude for a group (comma separated)
springdoc.group-configs[0].packages-to-exclude
List of Strings
.The list of packages to exclude for a group(comma separated)
List of Strings
. The list of packages to exclude for a group (comma separated)
springdoc.group-configs[0].produces-to-match
/*
List of Strings
.The list of produces mediaTypes to match (comma separated)
List of Strings
. The list of produces mediaTypes to match (comma separated)
springdoc.group-configs[0].consumes-to-match
/*
List of Strings
.The list of consumes mediaTypes to match (comma separated)
List of Strings
. The list of consumes mediaTypes to match (comma separated)
springdoc.group-configs[0].headers-to-match
/*
List of Strings
.The list of headers to match (comma separated)
List of Strings
. The list of headers to match (comma separated)
springdoc.webjars.prefix
/webjars
String
, To change the webjars prefix that is visible the URL of swagger-ui for spring-webflux.
String
. To change the webjars prefix that is visible the URL of swagger-ui for spring-webflux.
springdoc.api-docs.resolve-schema-properties
Boolean
. To make spring security login-endpoint visible.
springdoc.pre-loading-enabled
false
Boolean
. Pre-loading setting to load OpenAPI on application startup.
springdoc.pre-loading-locales
List of Strings
.The list of locales to load OpenAPI on application startup.(comma separated) If not specified, it will preload with the default Locale.
List of Strings
. The list of locales to load OpenAPI on application startup (comma separated). If not specified, it will preload with the default Locale.
springdoc.writer-with-order-by-keys
springdoc.enable-kotlin
true
Boolproperty resolver on @Schema (extensionean
. To enable Kotlin support.
Boolean
. To enable Kotlin support.
springdoc.enable-hateoas
springdoc.api-docs.version
-openapi_3_0
String
. To Choose OpenAPI 3.0
or OpenAPI 3.1
(using the value OPENAPI_3_1
).
openapi_3_1
String
. To choose OpenAPI 3.0
or OpenAPI 3.1
(using the value OPENAPI_3_1
).
springdoc.default-flat-param-object
false
Boolean
. Adjust indentation when parsing the @Operation
annotation in Kotlin.
springdoc.allowed-locales
List of Strings
. The list of allowed locales for OpenAPI (comma separated, for example US,fr-CA
).
springdoc.enable-extra-schemas
true
Boolean
. To enable default support for extra Schemas, from java.time
package like LocalTime
, Duration
, but also other Java classes like java.util.Locale
or java.nio.charset.Charset
springdoc.explicit-object-schema
false
Boolean
. Set explicit-object-schema to true
to always include type: object
in the schema, or to false
to omit type: object
.
springdoc.use-arbitrary-schemas
false
Boolean
. When set to true
, schemas without a defined type will be deserialized as an ArbitrarySchema
(with no type), instead of an ObjectSchema
with type: object
.
springdoc.swagger-ui.validatorUrl
By default, Swagger UI attempts to validate specs against swagger.io’s online validator. You can use this parameter to set a different validator URL, for example for locally deployed validators Validator Badge. Setting it to either none
, 127.0.0.1
or localhost
will disable validation.
By default, Swagger UI does not validate specs. You can use this parameter to set a validator URL, for example for against swagger.io’s online validator.
springdoc.swagger-ui.tryItOutEnabled
springdoc.swagger-ui.supportedSubmitMethods
Array=["get", "put", "post", "delete", "options", "head", "patch", "trace"]
. List of HTTP methods that have the "Try it out" feature enabled. An empty array disables "Try it out" for all operations. This does not filter the operations from the display.
Array=[get, put, post, delete, options, head, patch, trace]
. List of HTTP methods that have the "Try it out" feature enabled. An empty array disables "Try it out" for all operations. This does not filter the operations from the display.
springdoc.swagger-ui.queryConfigEnabled
springdoc.swagger-ui.validatorUrl
By default, Swagger UI attempts to validate specs against swagger.io’s online validator. You can use this parameter to set a different validator URL, for example for locally deployed validators Validator Badge. Setting it to either none
, 127.0.0.1
or localhost
will disable validation.
By default, Swagger UI does not validate specs. You can use this parameter to set a validator URL, for example for against swagger.io’s online validator.
springdoc.swagger-ui.tryItOutEnabled
springdoc.swagger-ui.supportedSubmitMethods
Array=["get", "put", "post", "delete", "options", "head", "patch", "trace"]
. List of HTTP methods that have the "Try it out" feature enabled. An empty array disables "Try it out" for all operations. This does not filter the operations from the display.
Array=[get, put, post, delete, options, head, patch, trace]
. List of HTTP methods that have the "Try it out" feature enabled. An empty array disables "Try it out" for all operations. This does not filter the operations from the display.
springdoc.swagger-ui.queryConfigEnabled
Boolean
. When true, automatically adds @ControllerAdvice responses to all the generated responses.
springdoc.api-docs.groups.enabled
true
Boolean
. To disable the springdoc-openapi groups.
springdoc.group-configs[0].group
String
.The group name
springdoc.swagger-ui.supportedSubmitMethods="get", "put", "post", "delete", "options", "head", "patch", "trace"+
springdoc.swagger-ui.supportedSubmitMethods=get, put, post, delete, options, head, patch, trace
---
-@Bean
+@Bean
@Primary
fun swaggerUiConfig(config: SwaggerUiConfigProperties): SwaggerUiConfigProperties {
config.showCommonExtensions = true
config.queryConfigEnabled = true
return config
}
----
@Bean
-public OpenApiCustomiser consumerTypeHeaderOpenAPICustomiser() {
-return openApi -> openApi.getPaths().values().stream().flatMap(pathItem -> pathItem.readOperations().stream())
- .forEach(operation -> operation.addParametersItem(new HeaderParameter().$ref("#/components/parameters/myConsumerTypeHeader")));
+public OpenApiCustomizer customerGlobalHeaderOpenApiCustomizer() {
+ return openApi -> openApi.getPaths().values().stream().flatMap(pathItem -> pathItem.readOperations().stream())
+ .forEach(operation -> operation.addParametersItem(new HeaderParameter().$ref("#/components/parameters/myGlobalHeader")));
}
springdoc-openapi
SNAPSHOT
To achieve that, you can on your pom.xml or your settings.xml the following section:
+To achieve that, configure your pom.xml file with the following <repositories>
section:
<repositories>
- <repository>
- <id>snapshots-repo</id>
- <url>https://s01.oss.sonatype.org/content/repositories/snapshots</url>
- <releases><enabled>false</enabled></releases>
- <snapshots><enabled>true</enabled></snapshots>
- </repository>
- </repositories>
+ <repositories>
+ <repository>
+ <name>Central Portal Snapshots</name>
+ <id>central-portal-snapshots</id>
+ <url>https://central.sonatype.com/repository/maven-snapshots/</url>
+ <releases>
+ <enabled>false</enabled>
+ </releases>
+ <snapshots>
+ <enabled>true</enabled>
+ </snapshots>
+ </repository>
+ </repositories>
Documentation can be available in yaml format as well, on the following path : /v3/api-docs.yaml
+Documentation will be available in yaml format as well, on the following path : /v3/api-docs.yaml
This is a community-based project, not maintained by the Spring Framework Contributors (Pivotal).
Documentation can be available in yaml format as well, on the following path : /v3/api-docs.yaml
+Documentation will be available in yaml format as well, on the following path : /v3/api-docs.yaml
Documentation can be available in yaml format as well, on the following path : /v3/api-docs.yaml
+Documentation will be available in yaml format as well, on the following path : /v3/api-docs.yaml
Add the library to the list of your project dependencies (No additional configuration is needed)
@@ -884,18 +876,6 @@Boolean
. When true, automatically adds @ControllerAdvice responses to all the generated responses.
springdoc.api-docs.groups.enabled
true
Boolean
. To disable the springdoc-openapi groups.
springdoc.group-configs[0].group
String
.The group name
springdoc.swagger-ui.validatorUrl
By default, Swagger UI attempts to validate specs against swagger.io’s online validator. You can use this parameter to set a different validator URL, for example for locally deployed validators Validator Badge. Setting it to either none
, 127.0.0.1
or localhost
will disable validation.
By default, Swagger UI does not validate specs. You can use this parameter to set a validator URL, for example for against swagger.io’s online validator.
springdoc.swagger-ui.tryItOutEnabled
false
true
Boolean
. Controls whether the "Try it out" section should be enabled by default.
springdoc.swagger-ui.supportedSubmitMethods
Array=["get", "put", "post", "delete", "options", "head", "patch", "trace"]
. List of HTTP methods that have the "Try it out" feature enabled. An empty array disables "Try it out" for all operations. This does not filter the operations from the display.
Array=[get, put, post, delete, options, head, patch, trace]
. List of HTTP methods that have the "Try it out" feature enabled. An empty array disables "Try it out" for all operations. This does not filter the operations from the display.
springdoc.swagger-ui.queryConfigEnabled
https://s01.oss.sonatype.org/content/repositories/snapshots/org/springdoc/
+https://central.sonatype.com/service/rest/repository/browse/maven-snapshots/org/springdoc/
---
-@Bean
+@Bean
@Primary
fun swaggerUiConfig(config: SwaggerUiConfigProperties): SwaggerUiConfigProperties {
config.showCommonExtensions = true
config.queryConfigEnabled = true
return config
}
----
@Bean
-public OpenApiCustomiser consumerTypeHeaderOpenAPICustomiser() {
-return openApi -> openApi.getPaths().values().stream().flatMap(pathItem -> pathItem.readOperations().stream())
- .forEach(operation -> operation.addParametersItem(new HeaderParameter().$ref("#/components/parameters/myConsumerTypeHeader")));
+public OpenApiCustomizer customerGlobalHeaderOpenApiCustomizer() {
+ return openApi -> openApi.getPaths().values().stream().flatMap(pathItem -> pathItem.readOperations().stream())
+ .forEach(operation -> operation.addParametersItem(new HeaderParameter().$ref("#/components/parameters/myGlobalHeader")));
}
springdoc-openapi
SNAPSHOT
To achieve that, you can on your pom.xml or your settings.xml the following section:
+To achieve that, configure your pom.xml file with the following <repositories>
section:
<repositories>
- <repository>
- <id>snapshots-repo</id>
- <url>https://s01.oss.sonatype.org/content/repositories/snapshots</url>
- <releases><enabled>false</enabled></releases>
- <snapshots><enabled>true</enabled></snapshots>
- </repository>
- </repositories>
+ <repositories>
+ <repository>
+ <name>Central Portal Snapshots</name>
+ <id>central-portal-snapshots</id>
+ <url>https://central.sonatype.com/repository/maven-snapshots/</url>
+ <releases>
+ <enabled>false</enabled>
+ </releases>
+ <snapshots>
+ <enabled>true</enabled>
+ </snapshots>
+ </repository>
+ </repositories>
This is a community-based project, not maintained by the Spring Framework Contributors (Pivotal).
- - - - diff --git a/docs/v1/migrating-from-springfox.html b/docs/v1/migrating-from-springfox.html index 7623a51..c9ae792 100644 --- a/docs/v1/migrating-from-springfox.html +++ b/docs/v1/migrating-from-springfox.html @@ -71,7 +71,7 @@Documentation can be available in yaml format as well, on the following path : /v3/api-docs.yaml
+Documentation will be available in yaml format as well, on the following path : /v3/api-docs.yaml
Add the library to the list of your project dependencies (No additional configuration is needed)
@@ -558,25 +558,13 @@https://s01.oss.sonatype.org/content/repositories/snapshots/org/springdoc/
+https://central.sonatype.com/service/rest/repository/browse/maven-snapshots/org/springdoc/
If you have any questions or concerns about this Policy or its implementation, you may contact us at support@springdoc.org.
springdoc.packages-to-scan
*
List of Strings
.The list of packages to scan (comma separated)
List of Strings
. The list of packages to scan (comma separated)
springdoc.paths-to-match
/*
List of Strings
.The list of paths to match (comma separated)
List of Strings
. The list of paths to match (comma separated)
springdoc.produces-to-match
/*
List of Strings
.The list of produces mediaTypes to match (comma separated)
List of Strings
. The list of produces mediaTypes to match (comma separated)
springdoc.headers-to-match
/*
List of Strings
.The list of headers to match (comma separated)
List of Strings
. The list of headers to match (comma separated)
springdoc.consumes-to-match
/*
List of Strings
.The list of consumes mediaTypes to match (comma separated)
List of Strings
. The list of consumes mediaTypes to match (comma separated)
springdoc.paths-to-exclude
List of Strings
.The list of paths to exclude (comma separated)
List of Strings
. The list of paths to exclude (comma separated)
springdoc.packages-to-exclude
List of Strings
.The list of packages to exclude (comma separated)
List of Strings
. The list of packages to exclude (comma separated)
springdoc.default-consumes-media-type
springdoc.default-produces-media-type
/
String
.The default produces media type.
String
. The default produces media type.
springdoc.cache.disabled
Boolean
. When true, automatically adds @ControllerAdvice responses to all the generated responses.
springdoc.api-docs.groups.enabled
true
Boolean
. To disable the springdoc-openapi groups.
springdoc.group-configs[0].group
String
.The group name
String
. The group name
springdoc.group-configs[0].display-name
String
.The display name of the group.
String
. The display name of the group.
springdoc.group-configs[0].packages-to-scan
*
List of Strings
.The list of packages to scan for a group (comma separated)
List of Strings
. The list of packages to scan for a group (comma separated)
springdoc.group-configs[0].paths-to-match
/*
List of Strings
.The list of paths to match for a group(comma separated)
List of Strings
. The list of paths to match for a group (comma separated)
springdoc.group-configs[0].paths-to-exclude
``
List of Strings
.The list of paths to exclude for a group(comma separated)
List of Strings
. The list of paths to exclude for a group (comma separated)
springdoc.group-configs[0].packages-to-exclude
List of Strings
.The list of packages to exclude for a group(comma separated)
List of Strings
. The list of packages to exclude for a group (comma separated)
springdoc.group-configs[0].produces-to-match
/*
List of Strings
.The list of produces mediaTypes to match (comma separated)
List of Strings
. The list of produces mediaTypes to match (comma separated)
springdoc.group-configs[0].consumes-to-match
/*
List of Strings
.The list of consumes mediaTypes to match (comma separated)
List of Strings
. The list of consumes mediaTypes to match (comma separated)
springdoc.group-configs[0].headers-to-match
/*
List of Strings
.The list of headers to match (comma separated)
List of Strings
. The list of headers to match (comma separated)
springdoc.webjars.prefix
/webjars
String
, To change the webjars prefix that is visible the URL of swagger-ui for spring-webflux.
String
. To change the webjars prefix that is visible the URL of swagger-ui for spring-webflux.
springdoc.api-docs.resolve-schema-properties
Boolean
. To make spring security login-endpoint visible.
springdoc.pre-loading-enabled
false
Boolean
. Pre-loading setting to load OpenAPI on application startup.
springdoc.pre-loading-locales
List of Strings
.The list of locales to load OpenAPI on application startup.(comma separated) If not specified, it will preload with the default Locale.
List of Strings
. The list of locales to load OpenAPI on application startup (comma separated). If not specified, it will preload with the default Locale.
springdoc.writer-with-order-by-keys
springdoc.enable-kotlin
true
Boolproperty resolver on @Schema (extensionean
. To enable Kotlin support.
Boolean
. To enable Kotlin support.
springdoc.enable-hateoas
springdoc.api-docs.version
-openapi_3_0
String
. To Choose OpenAPI 3.0
or OpenAPI 3.1
(using the value OPENAPI_3_1
).
openapi_3_1
String
. To choose OpenAPI 3.0
or OpenAPI 3.1
(using the value OPENAPI_3_1
).
springdoc.default-flat-param-object
false
Boolean
. Adjust indentation when parsing the @Operation
annotation in Kotlin.
springdoc.allowed-locales
List of Strings
. The list of allowed locales for OpenAPI (comma separated, for example US,fr-CA
).
springdoc.enable-extra-schemas
true
Boolean
. To enable default support for extra Schemas, from java.time
package like LocalTime
, Duration
, but also other Java classes like java.util.Locale
or java.nio.charset.Charset
springdoc.explicit-object-schema
false
Boolean
. Set explicit-object-schema to true
to always include type: object
in the schema, or to false
to omit type: object
.
springdoc.use-arbitrary-schemas
false
Boolean
. When set to true
, schemas without a defined type will be deserialized as an ArbitrarySchema
(with no type), instead of an ObjectSchema
with type: object
.
springdoc.swagger-ui.validatorUrl
By default, Swagger UI attempts to validate specs against swagger.io’s online validator. You can use this parameter to set a different validator URL, for example for locally deployed validators Validator Badge. Setting it to either none
, 127.0.0.1
or localhost
will disable validation.
By default, Swagger UI does not validate specs. You can use this parameter to set a validator URL, for example for against swagger.io’s online validator.
springdoc.swagger-ui.tryItOutEnabled
springdoc.swagger-ui.supportedSubmitMethods
Array=["get", "put", "post", "delete", "options", "head", "patch", "trace"]
. List of HTTP methods that have the "Try it out" feature enabled. An empty array disables "Try it out" for all operations. This does not filter the operations from the display.
Array=[get, put, post, delete, options, head, patch, trace]
. List of HTTP methods that have the "Try it out" feature enabled. An empty array disables "Try it out" for all operations. This does not filter the operations from the display.
springdoc.swagger-ui.queryConfigEnabled
springdoc.swagger-ui.validatorUrl
By default, Swagger UI attempts to validate specs against swagger.io’s online validator. You can use this parameter to set a different validator URL, for example for locally deployed validators Validator Badge. Setting it to either none
, 127.0.0.1
or localhost
will disable validation.
By default, Swagger UI does not validate specs. You can use this parameter to set a validator URL, for example for against swagger.io’s online validator.
springdoc.swagger-ui.tryItOutEnabled
false
true
Boolean
. Controls whether the "Try it out" section should be enabled by default.
springdoc.swagger-ui.supportedSubmitMethods
Array=["get", "put", "post", "delete", "options", "head", "patch", "trace"]
. List of HTTP methods that have the "Try it out" feature enabled. An empty array disables "Try it out" for all operations. This does not filter the operations from the display.
Array=[get, put, post, delete, options, head, patch, trace]
. List of HTTP methods that have the "Try it out" feature enabled. An empty array disables "Try it out" for all operations. This does not filter the operations from the display.
springdoc.swagger-ui.queryConfigEnabled
Parameter name | +Default Value | +Description | +
---|---|---|
springdoc.api-docs.path |
+
|
+
|
+
springdoc.api-docs.enabled |
+
|
+
|
+
springdoc.packages-to-scan |
+
|
+
|
+
springdoc.paths-to-match |
+
|
+
|
+
springdoc.produces-to-match |
+
|
+
|
+
springdoc.headers-to-match |
+
|
+
|
+
springdoc.consumes-to-match |
+
|
+
|
+
springdoc.paths-to-exclude |
++ |
|
+
springdoc.packages-to-exclude |
++ |
|
+
springdoc.default-consumes-media-type |
+
|
+
|
+
springdoc.default-produces-media-type |
+
|
+
|
+
springdoc.cache.disabled |
+
|
+
|
+
springdoc.show-actuator |
+
|
+
|
+
springdoc.auto-tag-classes |
+
|
+
|
+
springdoc.model-and-view-allowed |
+
|
+
|
+
springdoc.override-with-generic-response |
+
|
+
|
+
springdoc.group-configs[0].group |
++ |
|
+
springdoc.group-configs[0].display-name |
++ |
|
+
springdoc.group-configs[0].packages-to-scan |
+
|
+
|
+
springdoc.group-configs[0].paths-to-match |
+
|
+
|
+
springdoc.group-configs[0].paths-to-exclude |
+`` |
+
|
+
springdoc.group-configs[0].packages-to-exclude |
++ |
|
+
springdoc.group-configs[0].produces-to-match |
+
|
+
|
+
springdoc.group-configs[0].consumes-to-match |
+
|
+
|
+
springdoc.group-configs[0].headers-to-match |
+
|
+
|
+
springdoc.webjars.prefix |
+
|
+
|
+
springdoc.api-docs.resolve-schema-properties |
+
|
+
|
+
springdoc.remove-broken-reference-definitions |
+
|
+
|
+
springdoc.writer-with-default-pretty-printer |
+
|
+
|
+
springdoc.model-converters.deprecating-converter.enabled |
+
|
+
|
+
springdoc.model-converters.polymorphic-converter.enabled |
+
|
+
|
+
springdoc.model-converters.pageable-converter.enabled |
+
|
+
|
+
springdoc.model-converters.sort-converter.enabled |
+
|
+
|
+
springdoc.use-fqn |
+
|
+
|
+
springdoc.show-login-endpoint |
+
|
+
|
+
springdoc.pre-loading-locales |
++ |
|
+
springdoc.writer-with-order-by-keys |
+
|
+
|
+
springdoc.use-management-port |
+
|
+
|
+
springdoc.disable-i18n |
+
|
+
|
+
springdoc.show-spring-cloud-functions |
+
|
+
|
+
springdoc.enable-groovy |
+
|
+
|
+
springdoc.enable-spring-security |
+
|
+
|
+
springdoc.enable-kotlin |
+
|
+
|
+
springdoc.enable-hateoas |
+
|
+
|
+
springdoc.enable-data-rest |
+
|
+
|
+
springdoc.api-docs.version |
+
|
+
|
+
springdoc.default-flat-param-object |
+
|
+
|
+
springdoc.default-support-form-data |
+
|
+
|
+
springdoc.nullable-request-parameter-enabled |
+
|
+
|
+
springdoc.show-oauth2-endpoints |
+
|
+
|
+
springdoc.api-docs.resolve-extensions-properties |
+
|
+
|
+
springdoc.enable-default-api-docs |
+
|
+
|
+
springdoc.trim-kotlin-indent |
+
|
+
|
+
springdoc.allowed-locales |
++ |
|
+
springdoc.enable-extra-schemas |
+
|
+
|
+
springdoc.explicit-object-schema |
+
|
+
|
+
springdoc.use-arbitrary-schemas |
+
|
+
|
+
Demo Spring Boot 4 WebFlux with Functional endpoints OpenAPI 3
+You can define your own groups of API based on the combination of: API paths and packages to scan. Each group should have a unique groupName
.
+The OpenAPI description of this group, will be available by default on:
http://server:port/context-path/v3/api-docs/groupName
To enable the support of multiple OpenAPI definitions, a bean of type GroupedOpenApi
needs to be defined.
For the following Group definition(based on package path), the OpenAPI description URL will be : /v3/api-docs/stores
+@Bean
+public GroupedOpenApi storeOpenApi() {
+ String paths[] = {"/store/**"};
+ return GroupedOpenApi.builder().group("stores").pathsToMatch(paths)
+ .build();
+}
+
+For the following Group definition (based on package name), the OpenAPI description URL will be: /v3/api-docs/users
+@Bean
+public GroupedOpenApi userOpenApi() {
+ String packagesToscan[] = {"test.org.springdoc.api.app68.api.user"};
+ return GroupedOpenApi.builder().group("users").packagesToScan(packagesToscan)
+ .build();
+}
+
+For the following Group definition(based on path), the OpenAPI description URL will be: /v3/api-docs/pets
+@Bean
+public GroupedOpenApi petOpenApi() {
+ String paths[] = {"/pet/**"};
+ return GroupedOpenApi.builder().group("pets").pathsToMatch(paths)
+ .build();
+}
+
+For the following Group definition (based on package name and path), the OpenAPI description URL will be: /v3/api-docs/groups
+@Bean
+public GroupedOpenApi groupOpenApi() {
+ String paths[] = {"/v1/**"};
+ String packagesToscan[] = {"test.org.springdoc.api.app68.api.user", "test.org.springdoc.api.app68.api.store"};
+ return GroupedOpenApi.builder().group("groups").pathsToMatch(paths).packagesToScan(packagesToscan)
+ .build();
+}
+
+For more details about the usage, you can have a look at the following sample Test:
+The support of the swagger official properties is available on springdoc-openapi
. See Official documentation.
You can use the same swagger properties in the documentation as Spring Boot properties.
++ + | +
+All these properties should be declared with the following prefix: springdoc.swagger-ui
+ |
+
You can use the standard swagger-ui
property filter.
springdoc.swagger-ui.filter=group-a+
This property helps you disable only the UI.
+springdoc.swagger-ui.enabled=false+
You can set this property in your application.yml like so for example:
+springdoc.swagger-ui.doc-expansion= none+
swagger-ui
?For layout options, you can use swagger-ui configuration options. For example:
+springdoc.swagger-ui.layout=BaseLayout+
You can use the following springdoc-openapi
properties:
#For sorting endpoints alphabetically +springdoc.swagger-ui.operationsSorter=alpha +#For sorting tags alphabetically +springdoc.swagger-ui.tagsSorter=alpha+
You have to set the following property:
+springdoc.swagger-ui.supportedSubmitMethods=get, put, post, delete, options, head, patch, trace+
You should add @Schema(enumAsRef = true)
on your enum.
enumAsRef = true
to all enums ?Declare the following property:
+static { + io.swagger.v3.core.jackson.ModelResolver.enumsAsRef = true; +}+
You can set list of paths to include using the following property:
+springdoc.pathsToMatch=/v1, /api/balance/**+
You can set list of packages to include using the following property:
+springdoc.packagesToScan=package1, package2+
These can be set by creating a swaggerUiConfig
bean as follows:
@Bean
+@Primary
+fun swaggerUiConfig(config: SwaggerUiConfigProperties): SwaggerUiConfigProperties {
+ config.showCommonExtensions = true
+ config.queryConfigEnabled = true
+ return config
+}
+
+You can use the following annotation on the top of the field that you want to hide:
+@Schema(hidden = true)
@AuthenticationPrincipal
parameter from spring-security ?A solution workaround would be to use: @Parameter(hidden = true)
The projects that use spring-boot-starter-security
or spring-security-oauth2-authorization-server
should use:
springdoc-openapi-starter-webmvc-api
if they depend on spring-boot-starter-web
and they only need the access to the OpenAPI endpoints.
OR springdoc-openapi-starter-webmvc-ui
, if they depend on spring-boot-starter-web
and they also need the access to the swagger-ui.
OR springdoc-openapi-starter-webflux-api
if they depend on spring-boot-starter-webflux
and they only the access to the OpenAPI endpoints.
OR springdoc-openapi-starter-webflux-ui
, if they depend on spring-boot-starter-webflux
and they also need the access to the swagger-ui.
Yes. More details are available, in the gradle plugin section.
+You can use @Parameter(hidden = true)
springdoc-openapi
support Jersey?If you are using JAX-RS and as implementation Jersey (@Path
for example), we do not support it.
We only support exposing Rest Endpoints using Spring managed beans (@RestController
for example).
You can have a look at swagger-jaxrs2 project:
+ +springdoc-openapi
generate API only for @RestController
?@RestController
is equivalent to @Controller
+ @RequestMapping
on the type level.
For some legacy apps, we are constrained to still support both.
+If you need to hide the @Controller
on the type level, in this case, you can use: @Hidden
on controller level.
Please note this annotation can be also used to hide some methods from the generated documentation.
+@NotEmpty
@NotBlank
@PositiveOrZero
@NegativeOrZero
?Yes
+Pageable
(spring-data-commons) object to correct URL-Parameter in Swagger UI?The support for Pageable of spring-data-commons is available out-of-the box since springdoc-openapi v1.6.0
.
+For this, you have to combine @ParameterObject
annotation with the Pageable
type.
Before springdoc-openapi v1.6.0
:
You can use as well @ParameterObject
instead of @PageableAsQueryParam
for HTTP GET
methods.
static {
+ getConfig().replaceParameterObjectWithClass(org.springframework.data.domain.Pageable.class, Pageable.class)
+ .replaceParameterObjectWithClass(org.springframework.data.domain.PageRequest.class, Pageable.class);
+}
+
+Another solution, is to configure Pageable manually:
+you will have to declare the explicit mapping of Pageable fields as Query Params and add the @Parameter(hidden = true) Pageable pageable
on your pageable parameter.
You should also, declare the annotation @PageableAsQueryParam
provided by springdoc-openapi
on the method level, or declare your own if need to define your custom description, defaultValue, …
If you want to disable the support of spring Pageable Type, you can use:
+springdoc.model-converters.pageable-converter.enabled=false
++ + | +
+The property springdoc.model-converters.pageable-converter.enabled is only available since v1.5.11+
+ |
+
You could add a property allowableValues
, to @Parameter
. For example:
@GetMapping("/example")
+public Object example(@Parameter(name ="json", schema = @Schema(description = "var 1",type = "string", allowableValues = {"1", "2"}))
+String json) {
+ return null;
+}
+
+or you could override toString
on your enum:
@Override
+@JsonValue
+public String toString() {
+ return String.valueOf(action);
+}
+
+springdoc-openapi-starter-webmvc-ui
behind a reverse proxy?If your application is running behind a proxy, a load-balancer or in the cloud, the request information (like the host, port, scheme…) might change along the way. Your application may be running on 10.10.10.10:8080
, but HTTP clients should only see example.org
.
RFC7239 "Forwarded Headers" defines the Forwarded HTTP header; proxies can use this header to provide information about the original request. You can configure your application to read those headers and automatically use that information when creating links and sending them to clients in HTTP 302 responses, JSON documents or HTML pages. There are also non-standard headers, like X-Forwarded-Host
, X-Forwarded-Port
, X-Forwarded-Proto
, X-Forwarded-Ssl
, and X-Forwarded-Prefix
.
If the proxy adds the commonly used X-Forwarded-For
and X-Forwarded-Proto headers
, setting server.forward-headers-strategy to NATIVE is enough to support those. With this option, the Web servers themselves natively support this feature; you can check their specific documentation to learn about specific behavior.
You need to make sure the following header is set in your reverse proxy configuration: X-Forwarded-Prefix
For example, using Apache 2, configuration:
+RequestHeader set X-Forwarded-Prefix "/custom-path"+
Then, in your Spring Boot application make sure your application handles this header: X-Forwarded-For
. There are two ways to achieve this:
server.use-forward-headers=true+
If this is not enough, Spring Framework provides a ForwardedHeaderFilter
. You can register it as a Servlet Filter in your application by setting server.forward-headers-strategy is set to FRAMEWORK.
Since Spring Boot 2.2, this is the new property to handle reverse proxy headers:
+server.forward-headers-strategy=framework
+And you can add the following bean to your application:
+@Bean
+ForwardedHeaderFilter forwardedHeaderFilter() {
+ return new ForwardedHeaderFilter();
+}
+
+If you need to manually adjust the URL displayed in the Swagger UI, implement the ServerBaseUrlCustomizer
interface. This might be necessary to remove the port number, for example.
@Bean
+public class CustomServerBaseUrlCustomizer implements ServerBaseUrlCustomizer {
+ @Override
+ public String customize(String serverBaseUrl) {
+ try {
+ URL url = new URL(serverBaseUrl);
+ if (url.getHost().contains(".com")) {
+ serverBaseUrl = new URL(url.getProtocol(),url.getHost(),url.getFile()).toString();
+ }
+ } catch (MalformedURLException ex) {
+ // nothing we can do
+ }
+
+ return serverBaseUrl;
+ }
+}
+
+springdoc-openapi-starter-webmvc-ui
dependency breaks my public/index.html
welcome pageIf you already have static content on your root, and you don’t want it to be overridden by springdoc-openapi-starter-webmvc-ui
configuration, you can just define a custom configuration of the swagger-ui
, in order not to override the configuration of your files from in your context-root:
For example use:
+springdoc.swagger-ui.path= /swagger-ui/api-docs.html+
You can write your own implementation of OpenApiCustomizer
.
An example is available on:
+ +@Bean
+public OpenApiCustomizer consumerTypeHeaderOpenAPICustomizer() {
+return openApi -> openApi.getPaths().values().stream().flatMap(pathItem -> pathItem.readOperations().stream())
+ .forEach(operation -> operation.addParametersItem(new HeaderParameter().$ref("#/components/parameters/myConsumerTypeHeader")));
+}
+
++ + | +
+This bean OpenApiCustomizer will be applied to the Default OpenAPI only.
+ |
+
If you need the OpenApiCustomizer
to applied to GroupedOpenApi
as well, then use GlobalOpenApiCustomizer
instead.
It is be possible to handle as return an empty content as response using, one of the following syntaxes:
+content = @Content
content = @Content(schema = @Schema(hidden = true))
For example:
+@Operation(summary = "Get thing", responses = {
+ @ApiResponse(description = "Successful Operation", responseCode = "200", content = @Content(mediaType = "application/json", schema = @Schema(implementation = String.class))),
+ @ApiResponse(responseCode = "404", description = "Not found", content = @Content),
+ @ApiResponse(responseCode = "401", description = "Authentication Failure", content = @Content(schema = @Schema(hidden = true))) })
+@RequestMapping(path = "/testme", method = RequestMethod.GET)
+ResponseEntity<String> testme() {
+ return ResponseEntity.ok("Hello");
+}
+
+An overloaded method on the same class, with the same HTTP Method and path, will have as a result, only one OpenAPI Operation generated.
+In addition, it’s recommended to have the @Operation
in the level of one of the overloaded methods. Otherwise it might be overridden if it’s declared many times within the same overloaded method.
You can use springdoc-openapi-maven-plugin
for this functionality:
You can customise the output directory (property outputDir): The default value is: ${project.build.directory}
+Principal
, Locale
, HttpServletRequest
and HttpServletResponse
and other injectable parameters supported by Spring MVC are excluded.
Full documentation here:
+ +If you don’t want to ignore the types Principal
, Locale
, HttpServletRequest
, and others,:
SpringDocUtils.getConfig().removeRequestWrapperToIgnore(HttpServletRequest.class)
+
+You should add the @SecurityRequirement
tags to your protected APIs.
For example:
+@Operation(security = { @SecurityRequirement(name = "bearer-key") })+
And the security definition sample:
+@Bean
+ public OpenAPI customOpenAPI() {
+ return new OpenAPI()
+ .components(new Components()
+ .addSecuritySchemes("bearer-key",
+ new SecurityScheme().type(SecurityScheme.Type.HTTP).scheme("bearer").bearerFormat("JWT")));
+}
+
+OAS 3 was released in July 2017, and there was no release of springfox
to support OAS 3.
+springfox
covers for the moment only swagger 2 integration with Spring Boot. The latest release date is June 2018. So, in terms of maintenance there is a big lack of support lately.
We decided to move forward and share the library that we already used on our internal projects, with the community.
+The biggest difference with springfox
, is that we integrate new features not covered by springfox
:
The integration between Spring Boot and OpenAPI 3 standard.
+We rely on on swagger-annotations
and swagger-ui
only official libraries.
We support new features on Spring 5, like spring-webflux
with annotated and functional style.
We do our best to answer all the questions and address all issues or enhancement requests
+There is no relation between springdoc-openapi
and springfox
.If you want to migrate to OpenAPI 3:
Remove all the dependencies and the related code to springfox
+Add springdoc-openapi-starter-webmvc-ui
dependency
If you don’t want to serve the UI from your root path or there is a conflict with an existing configuration, you can just change the following property:
+springdoc.swagger-ui.path=/you-path/swagger-ui.html+
You may have global parameters with Standard OpenAPI description.
+If you need the definitions to appear globally (within every group), no matter if the group fulfills the conditions specified on the GroupedOpenApi , you can use OpenAPI Bean.
+You can define common parameters under parameters in the global components section and reference them elsewhere via $ref
. You can also define global header parameters.
For this, you can override to OpenAPI Bean, and set the global headers or parameters definition on the components level.
+@Bean
+public OpenAPI customOpenAPI(@Value("${springdoc.version}") String appVersion) {
+ return new OpenAPI()
+ .components(new Components().addSecuritySchemes("basicScheme", new SecurityScheme().type(SecurityScheme.Type.HTTP).scheme("basic"))
+ .addParameters("myHeader1", new Parameter().in("header").schema(new StringSchema()).name("myHeader1")).addHeaders("myHeader2", new Header().description("myHeader2 header").schema(new StringSchema())))
+ .info(new Info()
+ .title("Petstore API")
+ .version(appVersion)
+ .description("This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters.")
+ .termsOfService("http://swagger.io/terms/")
+ .license(new License().name("Apache 2.0").url("http://springdoc.org")));
+}
+
+You can use: @SecurityScheme
annotation.
Or you can define it programmatically, by overriding OpenAPI Bean:
+ @Bean
+ public OpenAPI customOpenAPI(@Value("${springdoc.version}") String appVersion) {
+ return new OpenAPI()
+ .components(new Components().addSecuritySchemes("basicScheme",
+ new SecurityScheme().type(SecurityScheme.Type.HTTP).scheme("basic")))
+ info(new Info().title("SpringShop API").version(appVersion)
+ .license(new License().name("Apache 2.0").url("http://springdoc.org")));
+ }
+
+You can use @io.swagger.v3.oas.annotations.Hidden
annotation at @RestController
, @RestControllerAdvice
and method level
The @Hidden
annotation on exception handler methods, is considered when building generic (error) responses from @ControllerAdvice
exception handlers.
Or use: @Operation(hidden = true)
For global SecurityScheme, you can add it inside your own OpenAPI definition:
+@Bean
+public OpenAPI customOpenAPI() {
+ return new OpenAPI().components(new Components()
+ .addSecuritySchemes("basicScheme", new SecurityScheme()
+ .type(SecurityScheme.Type.HTTP).scheme("basic"))).info(new Info().title("Custom API")
+ .version("100")).addTagsItem(new Tag().name("mytag"));
+}
+
+The support of spring property resolver for @Info
: title
* description
* version
* termsOfService
The support of spring property resolver for @Info.license
: name
* url
The support of spring property resolver for @Info.contact
: name
* email
* url
The support of spring property resolver for @Operation
: description
* summary
The support of spring property resolver for @Parameter
: description
* name
The support of spring property resolver for @ApiResponse
: description
Its also possible to declare security URLs for @OAuthFlow
: openIdConnectUrl
* authorizationUrl
* refreshUrl
* tokenUrl
The support of spring property resolver for @Schema
: name
* title
* description
, by setting springdoc.api-docs.resolve-schema-properties
to true
The support of spring property resolver for @ExtensionProperty
by setting springdoc.api-docs.resolve-extensions-properties
to true
Generating automatically server URL may be useful, if the documentation is not present.
+If the server annotations are present, they will be used instead.
+By default, the OpenAPI description is calculated once, and then cached.
+Sometimes the same swagger-ui is served behind internal and external proxies. some users want the server URL, to be computed on each http request.
+In order to disable springdoc cache, you will have to set the following property:
+springdoc.cache.disabled= true+
swagger-ui
?You should use the springdoc-openapi-core
dependency only:
<dependency>
+ <groupId>org.springdoc</groupId>
+ <artifactId>springdoc-openapi-starter-webmvc-api</artifactId>
+ <version>latest.version</version>
+</dependency>
+springdoc-openapi
endpoints ?Use the following property:
+springdoc.api-docs.enabled=false+
To hide the response element, using @Schema
annotation, as follows, at operation level:
@Operation(responses = @ApiResponse(responseCode = "200", content = @Content(schema = @Schema(hidden = true))))+
Or directly at @ApiResponses
level:
@ApiResponses(value = {@ApiResponse(responseCode = "200", content = @Content(schema = @Schema(hidden = true))) }) +OR +@ApiResponse(responseCode = "404", description = "Not found", content = @Content)+
swagger-ui
, when I set a different context-path?If you use different context-path:
+server.servlet.context-path= /foo+
The swagger-ui
will be available on the following URL:
http://server:port/foo/swagger-ui.html
You can Define your own OpenAPI Bean: If you need the definitions to appear globally (within every group), no matter if the group fulfills the conditions specified on the GroupedOpenApi , you can use OpenAPI Bean.
+@Bean
+public OpenAPI customOpenAPI(@Value("${springdoc.version}") String appVersion) {
+ return new OpenAPI()
+ .components(new Components().addSecuritySchemes("basicScheme",
+ new SecurityScheme().type(SecurityScheme.Type.HTTP).scheme("basic")))
+ .info(new Info().title("SpringShop API").version(appVersion)
+ .license(new License().name("Apache 2.0").url("http://springdoc.org")));
+}
+
+If you need the definitions to appear within a specific group, and respect the conditions specified on the GroupedOpenApi, you can add OpenApiCustomizer to your GroupedOpenApi definition.
+GroupedOpenApi.builder().group("users").pathsToMatch(paths).packagesToScan(packagedToMatch).addOpenApiCustomizer(customerGlobalHeaderOpenApiCustomizer())
+ .build()
+
+@Bean
+public OpenApiCustomizer customerGlobalHeaderOpenApiCustomizer() {
+ return openApi -> openApi.path("/foo",
+ new PathItem().get(new Operation().operationId("foo").responses(new ApiResponses()
+ .addApiResponse("default",new ApiResponse().description("")
+ .content(new Content().addMediaType("fatz", new MediaType()))))));
+}
+
+The source code of the application is available at the following GitHub repository:
+ +The library supports the main file types: MultipartFile
, @RequestPart
, FilePart
You can upload a file as follows:
+@PostMapping(value = "/upload", consumes = {MediaType.MULTIPART_FORM_DATA_VALUE})
+public ResponseEntity<?> upload(@Parameter(description = "file") final MultipartFile file) {
+ return null;
+}
+
+@PostMapping(value = "/uploadFileWithQuery", consumes = {MediaType.MULTIPART_FORM_DATA_VALUE})
+public ResponseEntity<?> uploadFileWithQuery(@Parameter(description = "file") @RequestPart("file") final MultipartFile file,
+ @Parameter(description = "An extra query parameter") @RequestParam String name) {
+ return null;
+}
+
+@PostMapping(value = "/uploadFileWithJson", consumes = {MediaType.MULTIPART_FORM_DATA_VALUE}, produces = {
+ MediaType.APPLICATION_JSON_VALUE})
+public ResponseEntity<?> uploadFileWithJson(
+ @RequestBody(content = @Content(encoding = @Encoding(name = "jsonRequest", contentType = MediaType.APPLICATION_JSON_VALUE)))
+ @Parameter(description = "An extra JSON payload sent with file") @RequestPart("jsonRequest") final JsonRequest jsonRequest,
+ @RequestPart("file") final MultipartFile file) {
+ return null;
+}
+
+Any @GetMapping
parameters is marked as required, even if @RequestParam
is missing.
You can add @Parameter(required=false)
annotation if you need different behaviour.
Query parameters with defaultValue
specified are marked as required.
springdoc-openapi
renders these methods as a single endpoint. It detects the overloaded endpoints, and generates parameters.schema.oneOf.
With this property, all the springdoc-openapi
auto-configuration beans are disabled:
springdoc.api-docs.enabled=false+
Then enable the minimal Beans configuration, by adding this Bean:
+@Bean
+SpringDocConfiguration springDocConfiguration(){
+ return new SpringDocConfiguration();
+}
+
+@Bean
+SpringDocConfigProperties springDocConfigProperties() {
+ return new SpringDocConfigProperties();
+}
+
+@Bean
+ObjectMapperProvider objectMapperProvider(SpringDocConfigProperties springDocConfigProperties){
+ return new ObjectMapperProvider(springDocConfigProperties);
+}
+
+Then configure, the path of your custom UI yaml file.
+springdoc.swagger-ui.url=/api-docs.yaml+
The OpenAPI 3 specification does not allow explicitly adding Authorization header.
+Note: Header parameters named Accept, Content-Type and Authorization are not allowed. To describe these headers
For more information, you can read:
+ +This is the default behaviour if your @Controller
doesn’t have annotation @ResponseBody
You can change your controllers to @RestControllers
. Or add @ResponseBody
+ @Controller
.
If its not possible, you can configure springdoc to scan you additional controller using SpringDocUtils. For example:
+static {
+ SpringDocUtils.getConfig().addRestControllers(HelloController.class);
+}
+
+You can load groups dynamically using spring-boot configuration files.
+Note that, for this usage, you don’t have to declare the GroupedOpenApi Bean.
+You need to declare the following properties, under the prefix springdoc.group-configs.
+For example:
+springdoc.group-configs[0].group=users +springdoc.group-configs[0].paths-to-match=/user/** +springdoc.group-configs[0].packages-to-scan=test.org.springdoc.api+
The list of properties under this prefix, are available here:
+You can use springdoc annotation @ParameterObject.
+Request parameter annotated with @ParameterObject will help adding each field of the parameter as a separate request parameter.
+This is compatible with Spring MVC request parameters mapping to POJO object.
+This annotation does not support nested parameter objects.
+POJO object must contain getters for fields with mandatory prefix get
. Otherwise, the swagger documentation will not show the fields of the annotated entity.
springdoc-openapi
SNAPSHOT ?For testing purposes only, you can test temporarily using the last springdoc-openapi
SNAPSHOT
To achieve that, configure your pom.xml file with the following <repositories>
section:
<repositories>
+ <repository>
+ <name>Central Portal Snapshots</name>
+ <id>central-portal-snapshots</id>
+ <url>https://central.sonatype.com/repository/maven-snapshots/</url>
+ <releases>
+ <enabled>false</enabled>
+ </releases>
+ <snapshots>
+ <enabled>true</enabled>
+ </snapshots>
+ </repository>
+ </repositories>
+springdoc-openapi
MonetaryAmount support ?If an application wants to enable the springdoc-openapi
support, it declares:
SpringDocUtils.getConfig().replaceWithClass(MonetaryAmount.class, org.springdoc.core.converters.models.MonetaryAmount.class);
+
+Another solution, without using springdoc-openapi MonetaryAmount, would be:
+SpringDocUtils.getConfig().replaceWithSchema(MonetaryAmount.class, new ObjectSchema()
+ .addProperties("amount", new NumberSchema()).example(99.96)
+ .addProperties("currency", new StringSchema().example("USD")));
+
+The properties springdoc.swagger-ui.urls.*
, are suitable to configure external (/v3/api-docs url).
+For example if you want to agreagte all the endpoints of other services, inside one single application.
+IMPORTANT: Don’t forget that CORS needs to be enabled as well.
If your file open-api.json, contains the OpenAPI documentation in OpenAPI 3 format. +Then simply declare: The file name can be anything you want, from the moment your declaration is consistent yaml or json OpenAPI Spec.
+ springdoc.swagger-ui.url=/open-api.json
+Then the file open-api.json, should be located in: src/main/resources/static +No additional configuration is needed.
+If you are using standard headers.( For example using spring-security headers) +If the CSRF Token is required, swagger-ui automatically sends the new XSRF-TOKEN during each HTTP REQUEST.
+If your XSRF-TOKEN isn’t standards-based, you can use a requestInterceptor to manually capture and attach the latest xsrf token to requests programmatically via spring resource transformer:
+Starting from release v1.4.4 of springdoc-openapi, a new property is added to enable CSRF support, while using standard header names:
+springdoc.swagger-ui.csrf.enabled=true
+You can use the following property:
+springdoc.swagger-ui.disable-swagger-default-url=true
+Yes, you can use it in conjunction with @ParameterObject
annotation.
+Also, the spring-boot spring.data.web.
and spring.data.rest.default.
properties are supported since v1.4.5
You can use the following property:
+springdoc.show-login-endpoint=true
+You can use the following property:
+springdoc.remove-broken-reference-definitions=false
+The whole idea of springdoc-openapi
is to get your documentation the closest to the code, with minimal code changes.
+If the code contains @Deprecated
, sprindoc-openapi
will consider its schema as Deprecated as well.
+If you want to declare a field on swagger as non deprecated, even with the java code, the field contains @Depreacted
,
+You can use the following property that is available since release v1.4.3:
springdoc.model-converters.deprecating-converter.enabled=false
+You can use the following property:
+springdoc.model-and-view-allowed=true
+You can use the following property:
+springdoc.writer-with-default-pretty-printer=true
+Complex objects are always resolved as a reference to a schema defined in components.
+For example let’s consider a Instance
class with an workAddress
and homeAddress
attribute of type Address
:
public class PersonDTO {
+
+ @JsonProperty
+ private String email;
+
+ @JsonProperty
+ private String firstName;
+
+ @JsonProperty
+ private String lastName;
+
+ @Schema(ref = "WorkAddressSchema")
+ @JsonProperty
+ private Address workAddress;
+
+ @Schema(ref = "HomeAddressSchema")
+ @JsonProperty
+ private Address homeAddress;
+
+}
+
+public class Address {
+
+ @JsonProperty
+ private String addressName;
+
+}
+
+If you want to define two different schemas for this class, you can set up 2 different schemas as follow:
+@Bean
+public OpenAPI customOpenAPI() {
+return new OpenAPI().components(new Components()
+.addSchemas("WorkAddressSchema", getSchemaWithDifferentDescription(Address.class, "work Address" ))
+.addSchemas("HomeAddressSchema", getSchemaWithDifferentDescription(Address.class, "home Address" )));
+}
+
+private Schema getSchemaWithDifferentDescription(Class className, String description){
+ResolvedSchema resolvedSchema = ModelConverters.getInstance()
+.resolveAsResolvedSchema(
+new AnnotatedType(className).resolveAsRef(false));
+return resolvedSchema.schema.description(description);
+}
+
+For example let’s consider a Instance
class with an email
attribute:
public class PersonDTO {
+
+ @JsonProperty
+ private String email;
+
+ @JsonProperty
+ private String firstName;
+
+ @JsonProperty
+ private String lastName;
+
+
+}
+
+If you want to define two different description for the email
, you can set up 2 different schemas as follow:
@Bean
+public OpenAPI customOpenAPI() {
+return new OpenAPI().components(new Components()
+.addSchemas("PersonDTO1", getFieldSchemaWithDifferentDescription(PersonDTO.class, "work email" ))
+.addSchemas("PersonDTO2", getFieldSchemaWithDifferentDescription(PersonDTO.class, "home email" )));
+}
+
+private Schema getFieldSchemaWithDifferentDescription(Class className, String description){
+ ResolvedSchema resolvedSchema = ModelConverters.getInstance()
+ .resolveAsResolvedSchema(
+ new AnnotatedType(className).resolveAsRef(false));
+ return resolvedSchema.schema.addProperties("email", new StringSchema().description(description));
+}
+
+You can customize swagger documentation static resources located in META-INF/resources/webjars/swagger-ui/{swagger.version}/
. The list of resources includes:
index.html
swagger-ui-bundle.js
swagger-ui.css
swagger-ui-standalone-preset.js
swagger-ui.css.map
swagger-ui-bundle.js.map
swagger-ui-standalone-preset.js.map
favicon-32x32.png
To do this, you need to extend the implementation of SwaggerIndexPageTransformer
public class SwaggerCodeBlockTransformer
+ extends SwaggerIndexPageTransformer {
+ // < constructor >
+ @Override
+ public Resource transform(HttpServletRequest request,
+ Resource resource,
+ ResourceTransformerChain transformer)
+ throws IOException {
+ if (resource.toString().contains("swagger-ui.css")) {
+ final InputStream is = resource.getInputStream();
+ final InputStreamReader isr = new InputStreamReader(is);
+ try (BufferedReader br = new BufferedReader(isr)) {
+ final String css = br.lines().collect(Collectors.joining());
+ final byte[] transformedContent = css.replace("old", "new").getBytes();
+ return new TransformedResource(resource, transformedContent);
+ } // AutoCloseable br > isr > is
+ }
+ return super.transform(request, resource, transformer);
+ }
+
+}
+
+Next, add transformer @Bean
to your @Configuration
@Configuration
+public class OpenApiConfig {
+ @Bean
+ public SwaggerIndexTransformer swaggerIndexTransformer(
+ SwaggerUiConfigProperties a,
+ SwaggerUiOAuthProperties b,
+ SwaggerUiConfigParameters c,
+ SwaggerWelcomeCommon d) {
+ return new SwaggerCodeBlockTransformer(a, b, c, d);
+ }
+}
+
+Illustrative example
+The native support available added in spring-boot 3. +If you have some time, do not hesitate to test it before the next release.
+For the OpenAPI REST endpoints, you just need to build your application with the spring native
profile.
If you give @OpenAPIDefinition
or @SecurityScheme
to a class that has no implementation, that class will disappear when you natively compile.
+To avoid this, give the class a @Configuration
.
@Configuration +@OpenAPIDefinition(info = @Info(title = "My App", description = "description")) +public class OpenAPIConfig { +}+
When your application is using spring without (spring-boot), you need to add beans and auto-configuration that are natively provided in spring-boot.
+For example, lets assume you want load the swagger-ui in spring-mvc application:
+You mainly, need to add the springdoc-openapi module
+<dependency>
+ <groupId>org.springdoc</groupId>
+ <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
+ <version>last.version</version>
+</dependency>
+If you don’t have the spring-boot and spring-boot-autoconfigure dependencies, you need to add them. And pay attention to the compatibility matrix, between you spring.version and spring-boot.version. For example, in this case (spring.version=5.1.12.RELEASE):
+ <dependency>
+ <groupId>org.springframework.boot</groupId>
+ <artifactId>spring-boot-autoconfigure</artifactId>
+ <version>3.3.3</version>
+ </dependency>
+Scan for the springdoc-openapi
'auto-configuration classes that spring-boot automatically loads for you.
Depending on your module, you can find them on the file: spring.factories
of each springdoc-openapi
module.
@Configuration
+@EnableWebMvc
+public class WebConfig implements WebApplicationInitializer {
+
+ @Override
+ public void onStartup(ServletContext servletContext) {
+ WebApplicationContext context = getContext();
+ servletContext.addListener(new ContextLoaderListener(context));
+ ServletRegistration.Dynamic dispatcher = servletContext.addServlet("RestServlet",
+ new DispatcherServlet(context));
+ dispatcher.setLoadOnStartup(1);
+ dispatcher.addMapping("/*");
+ }
+
+ private AnnotationConfigWebApplicationContext getContext() {
+ AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
+ context.register(this.getClass(),
+ SpringDocConfiguration.class,
+ SpringDocConfigProperties.class,
+ SpringDocSpecPropertiesConfiguration.class,
+ SpringDocWebMvcConfiguration.class,
+ MultipleOpenApiSupportConfiguration.class,
+ SwaggerConfig.class,
+ SwaggerUiConfigProperties.class,
+ SwaggerUiOAuthProperties.class,
+ );
+ return context;
+ }
+}
+
+Depending on your module, you can find them on the file: org.springframework.boot.autoconfigure.AutoConfiguration.imports
of each springdoc-openapi
module.
For groups usage make sure your GroupedOpenApi
Beans are scanned.
If additionally, you are using custom context path
: /my-servlet-path
. Make sure you declare the following property:
spring.mvc.servlet.path=/my-servlet-path+
springdoc-openapi
with spring-boot
?springdoc-openapi 3.x
is compatible with spring-boot 4
.
In general, you should only pick the last stable version as per today 3.0.0-M1.
+More precisely, this the exhaustive list of spring-boot versions against which springdoc-openapi
has been built:
Spring Boot Versions |
+Springdoc OpenAPI Versions |
+
|
+
|
+
Swagger UI unable to render definition
, when overriding the default spring registered HttpMessageConverter
?When overriding the default spring-boot registered HttpMessageConverter
, you should have ByteArrayHttpMessageConverter
registered as well to have proper springdoc-openapi
support.
converters.add(new ByteArrayHttpMessageConverter());
+ converters.add(new MappingJackson2HttpMessageConverter(jacksonBuilder.build()));
+
++ + | +
+Order is very important, when registering HttpMessageConverters .
+ |
+
The issue is caused by the changes introduced by Spring-Boot 3.2.0
+in particular for the Parameter Name Discovery.
+This can be fixed by adding the -parameters
arg to the Maven Compiler Plugin.
<plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-compiler-plugin</artifactId>
+ <configuration>
+ <parameters>true</parameters>
+ </configuration>
+</plugin>
+The library uses spring-boot application auto-configured packages to scan for the following annotations in spring beans: OpenAPIDefinition and Info. +These annotations declare, API Information: Title, version, licence, security, servers, tags, security and externalDocs. +For better performance of documentation generation, declare @OpenAPIDefinition and @SecurityScheme annotations within a spring managed bean.
+To generate documentation automatically, make sure all the methods declare the HTTP Code responses using the annotation: @ResponseStatus
+springdoc-openapi
endpointsIn order to disable the springdoc-openapi
endpoint (/v3/api-docs by default) use the following property:
# Disabling the /v3/api-docs endpoint
+springdoc.api-docs.enabled=false
+In order to disable the swagger-ui, use the following property:
+# Disabling the swagger-ui
+springdoc.swagger-ui.enabled=false
+The library supports the swagger-ui official properties:
+You need to declare swagger-ui properties as spring-boot properties. +All these properties should be declared with the following prefix: springdoc.swagger-ui
+Additionally, to @Hidden annotation from swagger-annotations, its possible to restrict the generated OpenAPI description using package or path configuration.
+For the list of packages to include, use the following property:
+# Packages to include
+springdoc.packagesToScan=com.package1, com.package2
+For the list of paths to include, use the following property:
+# Paths to include
+springdoc.pathsToMatch=/v1, /api/balance/**
+Since version v1.5.0, a functional DSL has been introduced, thanks to this enhancement in the spring-framework: #25938
+It’s an alternative functional API to the @RouterOperations
annotations.
This is a sample DSL, to generate OpenAPI description to the webflux/WebMvc.fn REST endpoints:
+@Bean
+RouterFunction<?> routes() {
+ return route().GET("/foo", HANDLER_FUNCTION, ops -> ops
+ .operationId("hello")
+ .parameter(parameterBuilder().name("key1").description("My key1 description"))
+ .parameter(parameterBuilder().name("key2").description("My key2 description"))
+ .response(responseBuilder().responseCode("200").description("This is normal response description"))
+ .response(responseBuilder().responseCode("404").description("This is another response description"))
+ ).build();
+}
+
+Here is the link for some sample codes:
+And the Demo code, using the functional endpoints DSL:
+Since version v1.3.8
, the support of functional endpoints has been added.
+Two main annotations have been added for this purpose: @RouterOperations
and @RouterOperation
.
Only REST APIs with the @RouterOperations
and @RouterOperation
can be displayed on the swagger-ui.
@RouterOperation
: It can be used alone, if the Router bean contains one single route related to the REST API..
+When using @RouterOperation, its not mandatory to fill the path
@RouterOperation
, can reference directly a spring Bean (beanClass property) and the underlying method (beanMethod property): Springdoc-openapi, will then inspect this method and the swagger annotations on this method level.
@Bean
+@RouterOperation(beanClass = EmployeeService.class, beanMethod = "findAllEmployees")
+RouterFunction<ServerResponse> getAllEmployeesRoute() {
+ return route(GET("/employees").and(accept(MediaType.APPLICATION_JSON)),
+ req -> ok().body(
+ employeeService().findAllEmployees(), Employee.class));
+}
+
+@RouterOperation
, contains the @Operation
annotation.
+The @Operation
annotation can also be placed on the bean method level if the property beanMethod is declared.
+ + | ++Don’t forget to set operationId which is mandatory. + | +
@Bean
+@RouterOperation(operation = @Operation(operationId = "findEmployeeById", summary = "Find purchase order by ID", tags = { "MyEmployee" },
+ parameters = { @Parameter(in = ParameterIn.PATH, name = "id", description = "Employee Id") },
+ responses = { @ApiResponse(responseCode = "200", description = "successful operation", content = @Content(schema = @Schema(implementation = Employee.class))),
+ @ApiResponse(responseCode = "400", description = "Invalid Employee ID supplied"),
+ @ApiResponse(responseCode = "404", description = "Employee not found") }))
+RouterFunction<ServerResponse> getEmployeeByIdRoute() {
+ return route(GET("/employees/{id}"),
+ req -> ok().body(
+ employeeRepository().findEmployeeById(req.pathVariable("id")), Employee.class));
+}
+
+@RouterOperations
: This annotation should be used if the Router bean contains multiple routes.
+When using RouterOperations, its mandatory to fill the path property.
A @RouterOperations
, contains many @RouterOperation
.
@RouterOperations({ @RouterOperation(path = "/getAllPersons", beanClass = PersonService.class, beanMethod = "getAll"),
+ @RouterOperation(path = "/getPerson/{id}", beanClass = PersonService.class, beanMethod = "getById"),
+ @RouterOperation(path = "/createPerson", beanClass = PersonService.class, beanMethod = "save"),
+ @RouterOperation(path = "/deletePerson/{id}", beanClass = PersonService.class, beanMethod = "delete") })
+@Bean
+public RouterFunction<ServerResponse> personRoute(PersonHandler handler) {
+ return RouterFunctions
+ .route(GET("/getAllPersons").and(accept(MediaType.APPLICATION_JSON)), handler::findAll)
+ .andRoute(GET("/getPerson/{id}").and(accept(MediaType.APPLICATION_STREAM_JSON)), handler::findById)
+ .andRoute(POST("/createPerson").and(accept(MediaType.APPLICATION_JSON)), handler::save)
+ .andRoute(DELETE("/deletePerson/{id}").and(accept(MediaType.APPLICATION_JSON)), handler::delete);
+}
+
+All the documentations filled using @RouterOperation, might be completed by the router function data.
+For that, @RouterOperation
fields must help identify uniquely the concerned route.
+springdoc-openpi
scans for a unique route related to a @RouterOperation
annotation, using on the following criteria:
by path
+by path and RequestMethod
+by path and produces
+by path and consumes
+by path and RequestMethod and produces
+by path and RequestMethod and consumes
+by path and produces and consumes
+by path and RequestMethod and produces and consumes
+Some code samples are available on GITHUB of demos:
+And some project tests: (from app69 to app75)
+For the integration between spring-boot and swagger-ui, add the library to the list of your project dependencies (No additional configuration is needed)
+ <dependency>
+ <groupId>org.springdoc</groupId>
+ <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
+ <version>3.0.0-M1</version>
+ </dependency>
+This will automatically deploy swagger-ui to a spring-boot application:
+Documentation will be available in HTML format, using the official swagger-ui jars
+The Swagger UI page will then be available at http://server:port/context-path/swagger-ui.html
and the OpenAPI description will be available at the following url for json format: http://server:port/context-path/v3/api-docs
server: The server name or IP
+port: The server port
+context-path: The context path of the application
+Documentation will be available in yaml format as well, on the following path : /v3/api-docs.yaml
++ + | ++For custom path of the swagger documentation in HTML format, add a custom springdoc property, in your spring-boot configuration file: . + | +
# swagger-ui custom path
+springdoc.swagger-ui.path=/swagger-ui.html
+springdoc-openapi
endpointsswagger-ui
?enumAsRef = true
to all enums ?@AuthenticationPrincipal
parameter from spring-security ?@Parameters
annotation supported ?springdoc-openapi
support Jersey?springdoc-openapi
generate API only for @RestController
?@NotEmpty
@NotBlank
@PositiveOrZero
@NegativeOrZero
?Pageable
(spring-data-commons) object to correct URL-Parameter in Swagger UI?springdoc-openapi-starter-webmvc-ui
behind a reverse proxy?@JsonView
annotations in Spring MVC APIs supported?springdoc-openapi-starter-webmvc-ui
dependency breaks my public/index.html
welcome pageswagger-ui
?springdoc-openapi
endpoints ?swagger-ui
, when I set a different context-path?@Parameter
inside @Operation
annotation?springdoc-openapi
SNAPSHOT ?springdoc-openapi
MonetaryAmount support ?springdoc-openapi
with spring-boot
?Swagger UI unable to render definition
, when overriding the default spring registered HttpMessageConverter
?springdoc-openapi
is on Open Collective. If you ❤️ this project consider becoming a sponsor.
This project is sponsored by
+springdoc-openapi
java library helps to automate the generation of API documentation using spring boot projects.
+springdoc-openapi
works by examining an application at runtime to infer API semantics based on spring configurations, class structure and various annotations.
Automatically generates documentation in JSON/YAML and HTML format APIs. +This documentation can be completed by comments using swagger-api annotations.
+This library supports:
+OpenAPI 3
+Spring-boot v4 (Java 17 & Jakarta EE 9)
+JSR-303, specifically for @NotNull, @Min, @Max, and @Size.
+Swagger-ui
+OAuth 2
+GraalVM native images
+The following video introduces the Library:
+This is a community-based project, not maintained by the Spring Framework Contributors (Pivotal).
+For the integration between spring-boot and swagger-ui, add the library to the list of your project dependencies (No additional configuration is needed)
+ <dependency>
+ <groupId>org.springdoc</groupId>
+ <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
+ <version>3.0.0-M1</version>
+ </dependency>
+This will automatically deploy swagger-ui to a spring-boot application:
+Documentation will be available in HTML format, using the official swagger-ui jars
+The Swagger UI page will then be available at http://server:port/context-path/swagger-ui.html
and the OpenAPI description will be available at the following url for json format: http://server:port/context-path/v3/api-docs
server: The server name or IP
+port: The server port
+context-path: The context path of the application
+Documentation will be available in yaml format as well, on the following path : /v3/api-docs.yaml
++ + | ++For custom path of the swagger documentation in HTML format, add a custom springdoc property, in your spring-boot configuration file: . + | +
# swagger-ui custom path
+springdoc.swagger-ui.path=/swagger-ui.html
+Documentation will be available at the following url for json format: http://server:port/context-path/v3/api-docs
server: The server name or IP
+port: The server port
+context-path: The context path of the application
+Documentation will be available in yaml format as well, on the following path : /v3/api-docs.yaml
+Add the library to the list of your project dependencies. (No additional configuration is needed)
+ <dependency>
+ <groupId>org.springdoc</groupId>
+ <artifactId>springdoc-openapi-starter-webmvc-api</artifactId>
+ <version>3.0.0-M1</version>
+ </dependency>
++ + | ++This dependency is relevant if you want to generate the OpenAPI description without using the swagger-ui. + | +
+ + | ++For custom path of the OpenAPI documentation in Json format, add a custom springdoc property, in your spring-boot configuration file: + | +
# /api-docs endpoint custom path
+springdoc.api-docs.path=/api-docs
+Documentation will be available in yaml format as well, on the following path : /v3/api-docs.yaml
+Add the library to the list of your project dependencies (No additional configuration is needed)
+ <dependency>
+ <groupId>org.springdoc</groupId>
+ <artifactId>springdoc-openapi-starter-webflux-api</artifactId>
+ <version>3.0.0-M1</version>
+ </dependency>
+The support for Spring Hateoas is available using the dependency springdoc-openapi-hateoas.
+The projects that use spring-boot-starter-hateoas
should use:
springdoc-openapi-starter-webmvc-api
if they need only the access to the OpenAPI endpoints
OR springdoc-openapi-starter-webmvc-ui
, if they need also the access to the swagger-ui
springdoc-openapi
project supports spring-boot-starter-data-rest
types like: @RepositoryRestResource
and QuerydslPredicate
annotations.
The projects that use spring-boot-starter-data-rest
should use:
springdoc-openapi-starter-webmvc-api
if they need only the access to the OpenAPI endpoints
OR springdoc-openapi-starter-webmvc-ui
, if they need also the access to the swagger-ui
springdoc-openapi
helps ignoring @AuthenticationPrincipal type in case it is used on REST Controllers.
springdoc-openapi
supports also exposing Oauth2 endpoints of spring-security-oauth2-authorization-server
.
The projects that use spring-boot-starter-security
or spring-security-oauth2-authorization-server
should use:
springdoc-openapi-starter-webmvc-api
if they depend on spring-boot-starter-web
and they only need the access to the OpenAPI endpoints.
OR springdoc-openapi-starter-webmvc-ui
, if they depend on spring-boot-starter-web
and they also need the access to the swagger-ui.
OR springdoc-openapi-starter-webflux-api
if they depend on spring-boot-starter-webflux
and they only the access to the OpenAPI endpoints.
OR springdoc-openapi-starter-webflux-ui
, if they depend on spring-boot-starter-webflux
and they also need the access to the swagger-ui.
In order to display spring-boot-actuator
endpoints, simply add the following property:
springdoc.show-actuator=true
+Starting from the release 1.5.1
, it will be possible to expose the swagger-ui and the openapi endpoints on actuator port.
+ + | ++The actuator management port has to be different from the application port. + | +
To expose the swagger-ui, on the management port, you should set
+springdoc.use-management-port=true
+# This property enables the openapi and swagger-ui endpoints to be exposed beneath the actuator base path.
+management.endpoints.web.exposure.include=openapi, swagger-ui
+Once enabled, you should also be able to see the springdoc-openapi endpoints under: (host and port depends on your settings)
+- http://serverName:managementPort/actuator
For example, if you have the following settings:
+Two endpoints will be available:
+REST API that holdes the OpenAPI definition:
+http://serverName:managementPort/actuator/openapi
An Endpoint, that routes to the swagger-ui:
+http://serverName:managementPort/actuator/swagger-ui
management.server.port=9090
+For the example, you should also be able to see the springdoc-openapi endpoints:
+http://serverName:9090/actuator
http://serverName:9090/actuator/swagger-ui
http://serverName:9090/actuator/openapi
All the path springdoc-openapi
properties are not applicable when springdoc.use-management-port=true
.
+ + | +
+If you want to reach the application endpoints, from the swagger-ui deployed beneath the actuator base path, using a different port from your application, CORS for your endpoints on your application level should be enabled.
+ |
+
Additionally, it is also possible to combine this property, with the existing property to display the actuator endpoints in the swagger-ui.
+springdoc.show-actuator=true
+Once enabled: +- A dedicated group for the actuator endpoints will be by default added. +- If no group is defined for the application, a default one will be added.
+The swagger-ui will be then accessible through the actuator port:
+http://serverName:managementPort/actuator/swagger-ui
If the management port is different from the application port and springdoc.use-management-port
is not defined but springdoc.show-actuator
is set to true:
The swagger-ui will be then accessible through the application port. For example: http://serverName:applicationPort/swagger-ui.html
A dedicated group for the actuator endpoints will be by default added.
+If no group is defined for the application, a default one will be added.
++ + | +
+If you want to reach the actuator endpoints for this case (different port from your application), CORS for your actuator endpoints should be enabled.
+ |
+
Note: The naming of these new endpoints beneath the actuator base path cannot be customized for now.
+spring-cloud-function-web
exposes Java Function as REST endpoint automatically.
+* Since version v1.6.3
, the support of functional endpoints has been added.
These starters will display the OpenAPI description of the spring-cloud-function-web
endpoints.
If you are using spring-web
, simply add the springdoc-openapi-starter-webmvc-ui
dependency.
If you are using spring-webflux
, simply add the springdoc-openapi-starter-webflux-ui
dependency.
The customisation of the output can be achieved programmatically through OpenApiCustomizer
or with the annotations: @RouterOperations
and @RouterOperation
.
+For annotation usage, you have:
+* @RouterOperation
: It can be used alone, if the customisation is related to a single REST API.
+When using @RouterOperation
, it’s not mandatory to fill the path
@RouterOperation
, contains the @Operation
annotation.
+The @Operation
annotation can also be placed on the bean method level if the property beanMethod is declared.
+ + | ++Don’t forget to set operationId which is mandatory. + | +
@Bean
+@RouterOperation(operation = @Operation(description = "Say hello", operationId = "hello", tags = "persons",
+ responses = @ApiResponse(responseCode = "200", content = @Content(schema = @Schema(implementation = PersonDTO.class)))))
+public Supplier<PersonDTO> helloSupplier() {
+ return () -> new PersonDTO();
+}
+
+@RouterOperations
: This annotation should be used to describe the multiple REST APIs exposed by spring-cloud-function-web
.
+When using RouterOperations
, it’s mandatory to fill the method property.
A @RouterOperations
, contains many @RouterOperation
.
@Bean
+@RouterOperations({
+ @RouterOperation(method = RequestMethod.GET, operation = @Operation(description = "Say hello GET", operationId = "lowercaseGET", tags = "persons")),
+ @RouterOperation(method = RequestMethod.POST, operation = @Operation(description = "Say hello POST", operationId = "lowercasePOST", tags = "positions"))
+})
+public Function<Flux<String>, Flux<String>> lowercase() {
+ return flux -> flux.map(value -> value.toLowerCase());
+}
+
+Some code samples are available on GITHUB of demos:
+springdoc-openapi
supports Kotlin types.
The projects that use Kotlin
should use:
springdoc-openapi-starter-webmvc-api
if they depend on spring-boot-starter-web
and they only need the access to the OpenAPI endpoints.
OR springdoc-openapi-starter-webmvc-ui
, if they depend on spring-boot-starter-web
and they also need the access to the swagger-ui.
OR springdoc-openapi-starter-webflux-api
if they depend on spring-boot-starter-webflux
and they only the access to the OpenAPI endpoints.
OR springdoc-openapi-starter-webflux-ui
, if they depend on spring-boot-starter-webflux
and they also need the access to the swagger-ui.
+ + | +
+In addition, your project should add jackson-module-kotlin as well to have the full support of Kotlin types:
+ |
+
<dependency>
+ <groupId>com.fasterxml.jackson.module</groupId>
+ <artifactId>jackson-module-kotlin</artifactId>
+ </dependency>
+The projects that use Groovy
should use:
springdoc-openapi-starter-webmvc-api
if they depend on spring-boot-starter-web
and they only need the access to the OpenAPI endpoints.
OR springdoc-openapi-starter-webmvc-ui
, if they depend on spring-boot-starter-web
and they also need the access to the swagger-ui.
OR springdoc-openapi-starter-webflux-api
if they depend on spring-boot-starter-webflux
and they only the access to the OpenAPI endpoints.
OR springdoc-openapi-starter-webflux-ui
, if they depend on spring-boot-starter-webflux
and they also need the access to the swagger-ui.
springdoc-openapi
can introspect Javadoc
annotations and comments:
The javadoc comment of a method: is resolved as the @Operation
description
@return
: is resolved as the @Operation
response description
The javadoc comment of an attribute: is resolved as '@Schema' description for this field.
+The projects that needs Javadoc
support should use:
springdoc-openapi-starter-webmvc-api
if they depend on spring-boot-starter-web
and they only need the access to the OpenAPI endpoints.
OR springdoc-openapi-starter-webmvc-ui
, if they depend on spring-boot-starter-web
and they also need the access to the swagger-ui.
OR springdoc-openapi-starter-webflux-api
if they depend on spring-boot-starter-webflux
and they only the access to the OpenAPI endpoints.
OR springdoc-openapi-starter-webflux-ui
, if they depend on spring-boot-starter-webflux
and they also need the access to the swagger-ui.
+ + | +
+In addition, your project should add therapi-runtime-javadoc to read Javadoc comments at runtime.
+Ensure that you add it as well as its annotation processor to your project’s dependencies. Otherwise, the Javadoc support will fail silently.
+ |
+
<!--Annotation processor -->
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-compiler-plugin</artifactId>
+ <configuration>
+ <annotationProcessorPaths>
+ <path>
+ <groupId>com.github.therapi</groupId>
+ <artifactId>therapi-runtime-javadoc-scribe</artifactId>
+ <version>0.15.0</version>
+ </path>
+ </annotationProcessorPaths>
+ </configuration>
+ </plugin>
+ </plugins>
+ </build>
+
+ <!-- Runtime library -->
+ <dependency>
+ <groupId>com.github.therapi</groupId>
+ <artifactId>therapi-runtime-javadoc</artifactId>
+ <version>0.15.0</version>
+ </dependency>
++ + | ++If both a swagger-annotation description and a javadoc comment are present. The value of the swagger-annotation description will be used. + | +
Starting from version v2.8.7
, springdoc-openapi
provides a BOM (Bill of Materials) to manage the dependencies of the project.
+You can declare it in your project as follows:
<dependencyManagement>
+ <dependencies>
+ <dependency>
+ <groupId>org.springdoc</groupId>
+ <artifactId>springdoc-openapi-bom</artifactId>
+ <version>3.0.0-M1</version>
+ <type>pom</type>
+ <scope>import</scope>
+ </dependency>
+ </dependencies>
+ </dependencyManagement>
+The library uses spring-boot application auto-configured packages to scan for the following annotations in spring beans: OpenAPIDefinition and Info. +These annotations declare, API Information: Title, version, licence, security, servers, tags, security and externalDocs. +For better performance of documentation generation, declare @OpenAPIDefinition and @SecurityScheme annotations within a spring managed bean.
+To generate documentation automatically, make sure all the methods declare the HTTP Code responses using the annotation: @ResponseStatus
+springdoc-openapi
endpointsIn order to disable the springdoc-openapi
endpoint (/v3/api-docs by default) use the following property:
# Disabling the /v3/api-docs endpoint
+springdoc.api-docs.enabled=false
+In order to disable the swagger-ui, use the following property:
+# Disabling the swagger-ui
+springdoc.swagger-ui.enabled=false
+The library supports the swagger-ui official properties:
+You need to declare swagger-ui properties as spring-boot properties. +All these properties should be declared with the following prefix: springdoc.swagger-ui
+Additionally, to @Hidden annotation from swagger-annotations, its possible to restrict the generated OpenAPI description using package or path configuration.
+For the list of packages to include, use the following property:
+# Packages to include
+springdoc.packagesToScan=com.package1, com.package2
+For the list of paths to include, use the following property:
+# Paths to include
+springdoc.pathsToMatch=/v1, /api/balance/**
+Since version v1.5.0, a functional DSL has been introduced, thanks to this enhancement in the spring-framework: #25938
+It’s an alternative functional API to the @RouterOperations
annotations.
This is a sample DSL, to generate OpenAPI description to the webflux/WebMvc.fn REST endpoints:
+@Bean
+RouterFunction<?> routes() {
+ return route().GET("/foo", HANDLER_FUNCTION, ops -> ops
+ .operationId("hello")
+ .parameter(parameterBuilder().name("key1").description("My key1 description"))
+ .parameter(parameterBuilder().name("key2").description("My key2 description"))
+ .response(responseBuilder().responseCode("200").description("This is normal response description"))
+ .response(responseBuilder().responseCode("404").description("This is another response description"))
+ ).build();
+}
+
+Here is the link for some sample codes:
+And the Demo code, using the functional endpoints DSL:
+Since version v1.3.8
, the support of functional endpoints has been added.
+Two main annotations have been added for this purpose: @RouterOperations
and @RouterOperation
.
Only REST APIs with the @RouterOperations
and @RouterOperation
can be displayed on the swagger-ui.
@RouterOperation
: It can be used alone, if the Router bean contains one single route related to the REST API..
+When using @RouterOperation, its not mandatory to fill the path
@RouterOperation
, can reference directly a spring Bean (beanClass property) and the underlying method (beanMethod property): Springdoc-openapi, will then inspect this method and the swagger annotations on this method level.
@Bean
+@RouterOperation(beanClass = EmployeeService.class, beanMethod = "findAllEmployees")
+RouterFunction<ServerResponse> getAllEmployeesRoute() {
+ return route(GET("/employees").and(accept(MediaType.APPLICATION_JSON)),
+ req -> ok().body(
+ employeeService().findAllEmployees(), Employee.class));
+}
+
+@RouterOperation
, contains the @Operation
annotation.
+The @Operation
annotation can also be placed on the bean method level if the property beanMethod is declared.
+ + | ++Don’t forget to set operationId which is mandatory. + | +
@Bean
+@RouterOperation(operation = @Operation(operationId = "findEmployeeById", summary = "Find purchase order by ID", tags = { "MyEmployee" },
+ parameters = { @Parameter(in = ParameterIn.PATH, name = "id", description = "Employee Id") },
+ responses = { @ApiResponse(responseCode = "200", description = "successful operation", content = @Content(schema = @Schema(implementation = Employee.class))),
+ @ApiResponse(responseCode = "400", description = "Invalid Employee ID supplied"),
+ @ApiResponse(responseCode = "404", description = "Employee not found") }))
+RouterFunction<ServerResponse> getEmployeeByIdRoute() {
+ return route(GET("/employees/{id}"),
+ req -> ok().body(
+ employeeRepository().findEmployeeById(req.pathVariable("id")), Employee.class));
+}
+
+@RouterOperations
: This annotation should be used if the Router bean contains multiple routes.
+When using RouterOperations, its mandatory to fill the path property.
A @RouterOperations
, contains many @RouterOperation
.
@RouterOperations({ @RouterOperation(path = "/getAllPersons", beanClass = PersonService.class, beanMethod = "getAll"),
+ @RouterOperation(path = "/getPerson/{id}", beanClass = PersonService.class, beanMethod = "getById"),
+ @RouterOperation(path = "/createPerson", beanClass = PersonService.class, beanMethod = "save"),
+ @RouterOperation(path = "/deletePerson/{id}", beanClass = PersonService.class, beanMethod = "delete") })
+@Bean
+public RouterFunction<ServerResponse> personRoute(PersonHandler handler) {
+ return RouterFunctions
+ .route(GET("/getAllPersons").and(accept(MediaType.APPLICATION_JSON)), handler::findAll)
+ .andRoute(GET("/getPerson/{id}").and(accept(MediaType.APPLICATION_STREAM_JSON)), handler::findById)
+ .andRoute(POST("/createPerson").and(accept(MediaType.APPLICATION_JSON)), handler::save)
+ .andRoute(DELETE("/deletePerson/{id}").and(accept(MediaType.APPLICATION_JSON)), handler::delete);
+}
+
+All the documentations filled using @RouterOperation, might be completed by the router function data.
+For that, @RouterOperation
fields must help identify uniquely the concerned route.
+springdoc-openpi
scans for a unique route related to a @RouterOperation
annotation, using on the following criteria:
by path
+by path and RequestMethod
+by path and produces
+by path and consumes
+by path and RequestMethod and produces
+by path and RequestMethod and consumes
+by path and produces and consumes
+by path and RequestMethod and produces and consumes
+Some code samples are available on GITHUB of demos:
+And some project tests: (from app69 to app75)
+springdoc-openapi
relies on standard spring configuration properties (yml or properties) using the standard files locations.
Parameter name | +Default Value | +Description | +
---|---|---|
springdoc.api-docs.path |
+
|
+
|
+
springdoc.api-docs.enabled |
+
|
+
|
+
springdoc.packages-to-scan |
+
|
+
|
+
springdoc.paths-to-match |
+
|
+
|
+
springdoc.produces-to-match |
+
|
+
|
+
springdoc.headers-to-match |
+
|
+
|
+
springdoc.consumes-to-match |
+
|
+
|
+
springdoc.paths-to-exclude |
++ |
|
+
springdoc.packages-to-exclude |
++ |
|
+
springdoc.default-consumes-media-type |
+
|
+
|
+
springdoc.default-produces-media-type |
+
|
+
|
+
springdoc.cache.disabled |
+
|
+
|
+
springdoc.show-actuator |
+
|
+
|
+
springdoc.auto-tag-classes |
+
|
+
|
+
springdoc.model-and-view-allowed |
+
|
+
|
+
springdoc.override-with-generic-response |
+
|
+
|
+
springdoc.group-configs[0].group |
++ |
|
+
springdoc.group-configs[0].display-name |
++ |
|
+
springdoc.group-configs[0].packages-to-scan |
+
|
+
|
+
springdoc.group-configs[0].paths-to-match |
+
|
+
|
+
springdoc.group-configs[0].paths-to-exclude |
+`` |
+
|
+
springdoc.group-configs[0].packages-to-exclude |
++ |
|
+
springdoc.group-configs[0].produces-to-match |
+
|
+
|
+
springdoc.group-configs[0].consumes-to-match |
+
|
+
|
+
springdoc.group-configs[0].headers-to-match |
+
|
+
|
+
springdoc.webjars.prefix |
+
|
+
|
+
springdoc.api-docs.resolve-schema-properties |
+
|
+
|
+
springdoc.remove-broken-reference-definitions |
+
|
+
|
+
springdoc.writer-with-default-pretty-printer |
+
|
+
|
+
springdoc.model-converters.deprecating-converter.enabled |
+
|
+
|
+
springdoc.model-converters.polymorphic-converter.enabled |
+
|
+
|
+
springdoc.model-converters.pageable-converter.enabled |
+
|
+
|
+
springdoc.model-converters.sort-converter.enabled |
+
|
+
|
+
springdoc.use-fqn |
+
|
+
|
+
springdoc.show-login-endpoint |
+
|
+
|
+
springdoc.pre-loading-locales |
++ |
|
+
springdoc.writer-with-order-by-keys |
+
|
+
|
+
springdoc.use-management-port |
+
|
+
|
+
springdoc.disable-i18n |
+
|
+
|
+
springdoc.show-spring-cloud-functions |
+
|
+
|
+
springdoc.enable-groovy |
+
|
+
|
+
springdoc.enable-spring-security |
+
|
+
|
+
springdoc.enable-kotlin |
+
|
+
|
+
springdoc.enable-hateoas |
+
|
+
|
+
springdoc.enable-data-rest |
+
|
+
|
+
springdoc.api-docs.version |
+
|
+
|
+
springdoc.default-flat-param-object |
+
|
+
|
+
springdoc.default-support-form-data |
+
|
+
|
+
springdoc.nullable-request-parameter-enabled |
+
|
+
|
+
springdoc.show-oauth2-endpoints |
+
|
+
|
+
springdoc.api-docs.resolve-extensions-properties |
+
|
+
|
+
springdoc.enable-default-api-docs |
+
|
+
|
+
springdoc.trim-kotlin-indent |
+
|
+
|
+
springdoc.allowed-locales |
++ |
|
+
springdoc.enable-extra-schemas |
+
|
+
|
+
springdoc.explicit-object-schema |
+
|
+
|
+
springdoc.use-arbitrary-schemas |
+
|
+
|
+
The support of the swagger-ui properties is available on springdoc-openapi
. See Official documentation.
You can use the same swagger-ui properties in the documentation as Spring Boot properties.
++ + | +
+All these properties should be declared with the following prefix: springdoc.swagger-ui
+ |
+
Parameter name | +Default Value | +Description | +
---|---|---|
springdoc.swagger-ui.path |
+
|
+
|
+
springdoc.swagger-ui.enabled |
+
|
+
|
+
springdoc.swagger-ui.configUrl |
+
|
+
|
+
springdoc.swagger-ui.layout |
+
|
+
|
+
springdoc.swagger-ui.validatorUrl |
++ | By default, Swagger UI does not validate specs. You can use this parameter to set a validator URL, for example for against swagger.io’s online validator. |
+
springdoc.swagger-ui.tryItOutEnabled |
+
|
+
|
+
springdoc.swagger-ui.filter |
+
|
+
|
+
springdoc.swagger-ui.operationsSorter |
++ |
|
+
springdoc.swagger-ui.tagsSorter |
++ |
|
+
springdoc.swagger-ui.oauth2RedirectUrl |
+
|
+
|
+
springdoc.swagger-ui.displayOperationId |
+
|
+
|
+
springdoc.swagger-ui.displayRequestDuration |
+
|
+
|
+
springdoc.swagger-ui.deepLinking |
+
|
+
|
+
springdoc.swagger-ui.defaultModelsExpandDepth |
+
|
+
|
+
springdoc.swagger-ui.defaultModelExpandDepth |
+
|
+
|
+
springdoc.swagger-ui.defaultModelRendering |
++ |
|
+
springdoc.swagger-ui.docExpansion |
++ |
|
+
springdoc.swagger-ui.maxDisplayedTags |
++ |
|
+
springdoc.swagger-ui.showExtensions |
+
|
+
|
+
springdoc.swagger-ui.url |
++ |
|
+
springdoc.swagger-ui.showCommonExtensions |
+
|
+
|
+
springdoc.swagger-ui.supportedSubmitMethods |
++ |
|
+
springdoc.swagger-ui.queryConfigEnabled |
+
|
+
|
+
springdoc.swagger-ui.oauth. additionalQueryStringParams |
++ |
|
+
springdoc.swagger-ui.disable-swagger-default-url |
+
|
+
|
+
springdoc.swagger-ui.urls[0].url |
++ |
|
+
springdoc.swagger-ui.urls[0].name |
++ |
|
+
springdoc.swagger-ui.urlsPrimaryName |
++ |
|
+
springdoc.swagger-ui.oauth.clientId |
++ |
|
+
springdoc.swagger-ui.oauth.clientSecret |
++ |
|
+
springdoc.swagger-ui.oauth.realm |
++ |
|
+
springdoc.swagger-ui.oauth.appName |
++ |
|
+
springdoc.swagger-ui.oauth.scopeSeparator |
++ |
|
+
springdoc.swagger-ui.csrf.enabled |
+
|
+
|
+
springdoc.swagger-ui.csrf.use-local-storage |
+
|
+
|
+
springdoc.swagger-ui.csrf.use-session-storage |
+
|
+
|
+
springdoc.swagger-ui.csrf.cookie-name |
+
|
+
|
+
springdoc.swagger-ui.csrf.header-name |
+
|
+
|
+
springdoc.swagger-ui.syntaxHighlight.activated |
+
|
+
|
+
springdoc.swagger-ui.syntaxHighlight.theme |
+
|
+
|
+
springdoc.swagger-ui.oauth. useBasicAuthentication WithAccessCodeGrant |
+
|
+
|
+
springdoc.swagger-ui.oauth. usePkceWithAuthorization CodeGrant |
+
|
+
|
+
springdoc.swagger-ui.persistAuthorization |
+
|
+
|
+
springdoc.swagger-ui.use-root-path |
+
|
+
|
+
The aim of springdoc-openapi-maven-plugin
is to generate json and yaml OpenAPI description during build time.
+The plugin works during integration-tests phase, and generate the OpenAPI description.
+The plugin works in conjunction with spring-boot-maven plugin.
You can test it during the integration tests phase using the maven command:
+mvn verify
+In order to use this functionality, you need to add the plugin declaration on the plugins section of your pom.xml:
+<plugin>
+ <groupId>org.springframework.boot</groupId>
+ <artifactId>spring-boot-maven-plugin</artifactId>
+ <version>${spring-boot-maven-plugin.version}</version>
+ <configuration>
+ <jvmArguments>-Dspring.application.admin.enabled=true</jvmArguments>
+ </configuration>
+ <executions>
+ <execution>
+ <goals>
+ <goal>start</goal>
+ <goal>stop</goal>
+ </goals>
+ </execution>
+ </executions>
+</plugin>
+<plugin>
+ <groupId>org.springdoc</groupId>
+ <artifactId>springdoc-openapi-maven-plugin</artifactId>
+ <version>1.5</version>
+ <executions>
+ <execution>
+ <id>integration-test</id>
+ <goals>
+ <goal>generate</goal>
+ </goals>
+ </execution>
+ </executions>
+</plugin>
+For more custom settings of the springdoc-openapi-maven-plugin, you can consult the plugin documentation:
+This plugin allows you to generate an OpenAPI 3 specification for a Spring Boot application from a Gradle build.
+plugins {
+ id("org.springframework.boot") version "3.1.2"
+ id("org.springdoc.openapi-gradle-plugin") version "1.9.0"
+}
+
+When you add this plugin and its runtime dependency plugins to your build file, the plugin creates the following tasks:
+forkedSpringBootRun
+generateOpenApiDocs
+gradle clean generateOpenApiDocs
+For more custom configuration of springdoc-openapi-gradle-plugin
,you can consult the plugin documentation:
Demo Spring Boot 4 WebFlux with Functional endpoints OpenAPI 3
+Remove springfox and swagger 2 dependencies. Add springdoc-openapi-starter-webmvc-ui
dependency instead.
<dependency>
+ <groupId>org.springdoc</groupId>
+ <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
+ <version>3.0.0-M1</version>
+ </dependency>
+Replace swagger 2 annotations with swagger 3 annotations (it is already included with springdoc-openapi-starter-webmvc-ui
dependency).
+Package for swagger 3 annotations is io.swagger.v3.oas.annotations
.
@Api
→ @Tag
@ApiIgnore
→ @Parameter(hidden = true)
or @Operation(hidden = true)
or @Hidden
@ApiImplicitParam
→ @Parameter
@ApiImplicitParams
→ @Parameters
@ApiModel
→ @Schema
@ApiModelProperty(allowEmptyValue = true)
→ @Schema(nullable = true)
@ApiModelProperty
→ @Schema
@ApiOperation(value = "foo", notes = "bar")
→ @Operation(summary = "foo", description = "bar")
@ApiParam
→ @Parameter
@ApiResponse(code = 404, message = "foo")
→ @ApiResponse(responseCode = "404", description = "foo")
This step is optional: Only if you have multiple Docket
beans replace them with GroupedOpenApi
beans.
Before:
+ @Bean
+ public Docket publicApi() {
+ return new Docket(DocumentationType.SWAGGER_2)
+ .select()
+ .apis(RequestHandlerSelectors.basePackage("org.github.springshop.web.public"))
+ .paths(PathSelectors.regex("/public.*"))
+ .build()
+ .groupName("springshop-public")
+ .apiInfo(apiInfo());
+ }
+
+ @Bean
+ public Docket adminApi() {
+ return new Docket(DocumentationType.SWAGGER_2)
+ .select()
+ .apis(RequestHandlerSelectors.basePackage("org.github.springshop.web.admin"))
+ .paths(PathSelectors.regex("/admin.*"))
+ .apis(RequestHandlerSelectors.withMethodAnnotation(Admin.class))
+ .build()
+ .groupName("springshop-admin")
+ .apiInfo(apiInfo());
+ }
+
+Now:
+ @Bean
+ public GroupedOpenApi publicApi() {
+ return GroupedOpenApi.builder()
+ .group("springshop-public")
+ .pathsToMatch("/public/**")
+ .build();
+ }
+ @Bean
+ public GroupedOpenApi adminApi() {
+ return GroupedOpenApi.builder()
+ .group("springshop-admin")
+ .pathsToMatch("/admin/**")
+ .addOpenApiMethodFilter(method -> method.isAnnotationPresent(Admin.class))
+ .build();
+ }
+
+If you have only one Docket
— remove it and instead add properties to your application.properties
:
springdoc.packagesToScan=package1, package2
+springdoc.pathsToMatch=/v1, /api/balance/**
+Add bean of OpenAPI
type. See example:
@Bean
+ public OpenAPI springShopOpenAPI() {
+ return new OpenAPI()
+ .info(new Info().title("SpringShop API")
+ .description("Spring shop sample application")
+ .version("v0.0.1")
+ .license(new License().name("Apache 2.0").url("http://springdoc.org")))
+ .externalDocs(new ExternalDocumentation()
+ .description("SpringShop Wiki Documentation")
+ .url("https://springshop.wiki.github.org/docs"));
+ }
+
+If the swagger-ui is served behind a proxy:
+ +To customise the Swagger UI
+To hide an operation or a controller from documentation
+ +springdoc-openapi
is on Open Collective.
If you ❤️ this project consider becoming a sponsor.
+This money is used to cover project expenses and your donation will help the project live and grow successfully.
+Thank you to our bronze sponsors!
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Bronze sponsors donate $50 per month to the project, and get the following benefits:
+You will receive a Sponsor badge 🎖!. Visibility on the front page of springdoc.org in the welcome
page (about 55,000 views/month on May, 2022).
“Thank you” tweet from `springdoc team'.
+Silver sponsors donate $100 per month to the project, and get the following benefits:
+Same benefits as bronze sponsors (visibility on main pages, and thank you tweet).
+The ability to get support for 2 issues
every month, non transferable.
If issues are not created by the end of the month, it is lost
+Gold sponsors donate $500 per month to the project, and get the following benefits:
+Same benefits as silver sponsors (visibility on main pages, and thank you tweet).
+The ability to get support for 10 issues
every month, non transferable.
Company logos on all springdoc.org page footers
+If issues are not created by the end of the month, the remaining ones are lost.
+Thank you to The Spring Team for sharing all relevant resources around Spring projects.
+Thanks a lot JetBrains for supporting springdoc-openapi project.
+You can define your own groups of API based on the combination of: API paths and packages to scan. Each group should have a unique groupName
.
+The OpenAPI description of this group, will be available by default on:
http://server:port/context-path/v3/api-docs/groupName
To enable the support of multiple OpenAPI definitions, a bean of type GroupedOpenApi
needs to be defined.
For the following Group definition(based on package path), the OpenAPI description URL will be : /v3/api-docs/stores
+@Bean
+public GroupedOpenApi storeOpenApi() {
+ String paths[] = {"/store/**"};
+ return GroupedOpenApi.builder().group("stores").pathsToMatch(paths)
+ .build();
+}
+
+For the following Group definition (based on package name), the OpenAPI description URL will be: /v3/api-docs/users
+@Bean
+public GroupedOpenApi userOpenApi() {
+ String packagesToscan[] = {"test.org.springdoc.api.app68.api.user"};
+ return GroupedOpenApi.builder().group("users").packagesToScan(packagesToscan)
+ .build();
+}
+
+For the following Group definition(based on path), the OpenAPI description URL will be: /v3/api-docs/pets
+@Bean
+public GroupedOpenApi petOpenApi() {
+ String paths[] = {"/pet/**"};
+ return GroupedOpenApi.builder().group("pets").pathsToMatch(paths)
+ .build();
+}
+
+For the following Group definition (based on package name and path), the OpenAPI description URL will be: /v3/api-docs/groups
+@Bean
+public GroupedOpenApi groupOpenApi() {
+ String paths[] = {"/v1/**"};
+ String packagesToscan[] = {"test.org.springdoc.api.app68.api.user", "test.org.springdoc.api.app68.api.store"};
+ return GroupedOpenApi.builder().group("groups").pathsToMatch(paths).packagesToScan(packagesToscan)
+ .build();
+}
+
+For more details about the usage, you can have a look at the following sample Test:
+The support of the swagger official properties is available on springdoc-openapi
. See Official documentation.
You can use the same swagger properties in the documentation as Spring Boot properties.
++ + | +
+All these properties should be declared with the following prefix: springdoc.swagger-ui
+ |
+
You can use the standard swagger-ui
property filter.
springdoc.swagger-ui.filter=group-a+
This property helps you disable only the UI.
+springdoc.swagger-ui.enabled=false+
You can set this property in your application.yml like so for example:
+springdoc.swagger-ui.doc-expansion= none+
swagger-ui
?For layout options, you can use swagger-ui configuration options. For example:
+springdoc.swagger-ui.layout=BaseLayout+
You can use the following springdoc-openapi
properties:
#For sorting endpoints alphabetically +springdoc.swagger-ui.operationsSorter=alpha +#For sorting tags alphabetically +springdoc.swagger-ui.tagsSorter=alpha+
You have to set the following property:
+springdoc.swagger-ui.supportedSubmitMethods=get, put, post, delete, options, head, patch, trace+
You should add @Schema(enumAsRef = true)
on your enum.
enumAsRef = true
to all enums ?Declare the following property:
+static { + io.swagger.v3.core.jackson.ModelResolver.enumsAsRef = true; +}+
You can set list of paths to include using the following property:
+springdoc.pathsToMatch=/v1, /api/balance/**+
You can set list of packages to include using the following property:
+springdoc.packagesToScan=package1, package2+
These can be set by creating a swaggerUiConfig
bean as follows:
@Bean
+@Primary
+fun swaggerUiConfig(config: SwaggerUiConfigProperties): SwaggerUiConfigProperties {
+ config.showCommonExtensions = true
+ config.queryConfigEnabled = true
+ return config
+}
+
+You can use the following annotation on the top of the field that you want to hide:
+@Schema(hidden = true)
@AuthenticationPrincipal
parameter from spring-security ?A solution workaround would be to use: @Parameter(hidden = true)
The projects that use spring-boot-starter-security
or spring-security-oauth2-authorization-server
should use:
springdoc-openapi-starter-webmvc-api
if they depend on spring-boot-starter-web
and they only need the access to the OpenAPI endpoints.
OR springdoc-openapi-starter-webmvc-ui
, if they depend on spring-boot-starter-web
and they also need the access to the swagger-ui.
OR springdoc-openapi-starter-webflux-api
if they depend on spring-boot-starter-webflux
and they only the access to the OpenAPI endpoints.
OR springdoc-openapi-starter-webflux-ui
, if they depend on spring-boot-starter-webflux
and they also need the access to the swagger-ui.
Yes. More details are available, in the gradle plugin section.
+You can use @Parameter(hidden = true)
springdoc-openapi
support Jersey?If you are using JAX-RS and as implementation Jersey (@Path
for example), we do not support it.
We only support exposing Rest Endpoints using Spring managed beans (@RestController
for example).
You can have a look at swagger-jaxrs2 project:
+ +springdoc-openapi
generate API only for @RestController
?@RestController
is equivalent to @Controller
+ @RequestMapping
on the type level.
For some legacy apps, we are constrained to still support both.
+If you need to hide the @Controller
on the type level, in this case, you can use: @Hidden
on controller level.
Please note this annotation can be also used to hide some methods from the generated documentation.
+@NotEmpty
@NotBlank
@PositiveOrZero
@NegativeOrZero
?Yes
+Pageable
(spring-data-commons) object to correct URL-Parameter in Swagger UI?The support for Pageable of spring-data-commons is available out-of-the box since springdoc-openapi v1.6.0
.
+For this, you have to combine @ParameterObject
annotation with the Pageable
type.
Before springdoc-openapi v1.6.0
:
You can use as well @ParameterObject
instead of @PageableAsQueryParam
for HTTP GET
methods.
static {
+ getConfig().replaceParameterObjectWithClass(org.springframework.data.domain.Pageable.class, Pageable.class)
+ .replaceParameterObjectWithClass(org.springframework.data.domain.PageRequest.class, Pageable.class);
+}
+
+Another solution, is to configure Pageable manually:
+you will have to declare the explicit mapping of Pageable fields as Query Params and add the @Parameter(hidden = true) Pageable pageable
on your pageable parameter.
You should also, declare the annotation @PageableAsQueryParam
provided by springdoc-openapi
on the method level, or declare your own if need to define your custom description, defaultValue, …
If you want to disable the support of spring Pageable Type, you can use:
+springdoc.model-converters.pageable-converter.enabled=false
++ + | +
+The property springdoc.model-converters.pageable-converter.enabled is only available since v1.5.11+
+ |
+
You could add a property allowableValues
, to @Parameter
. For example:
@GetMapping("/example")
+public Object example(@Parameter(name ="json", schema = @Schema(description = "var 1",type = "string", allowableValues = {"1", "2"}))
+String json) {
+ return null;
+}
+
+or you could override toString
on your enum:
@Override
+@JsonValue
+public String toString() {
+ return String.valueOf(action);
+}
+
+springdoc-openapi-starter-webmvc-ui
behind a reverse proxy?If your application is running behind a proxy, a load-balancer or in the cloud, the request information (like the host, port, scheme…) might change along the way. Your application may be running on 10.10.10.10:8080
, but HTTP clients should only see example.org
.
RFC7239 "Forwarded Headers" defines the Forwarded HTTP header; proxies can use this header to provide information about the original request. You can configure your application to read those headers and automatically use that information when creating links and sending them to clients in HTTP 302 responses, JSON documents or HTML pages. There are also non-standard headers, like X-Forwarded-Host
, X-Forwarded-Port
, X-Forwarded-Proto
, X-Forwarded-Ssl
, and X-Forwarded-Prefix
.
If the proxy adds the commonly used X-Forwarded-For
and X-Forwarded-Proto headers
, setting server.forward-headers-strategy to NATIVE is enough to support those. With this option, the Web servers themselves natively support this feature; you can check their specific documentation to learn about specific behavior.
You need to make sure the following header is set in your reverse proxy configuration: X-Forwarded-Prefix
For example, using Apache 2, configuration:
+RequestHeader set X-Forwarded-Prefix "/custom-path"+
Then, in your Spring Boot application make sure your application handles this header: X-Forwarded-For
. There are two ways to achieve this:
server.use-forward-headers=true+
If this is not enough, Spring Framework provides a ForwardedHeaderFilter
. You can register it as a Servlet Filter in your application by setting server.forward-headers-strategy is set to FRAMEWORK.
Since Spring Boot 2.2, this is the new property to handle reverse proxy headers:
+server.forward-headers-strategy=framework
+And you can add the following bean to your application:
+@Bean
+ForwardedHeaderFilter forwardedHeaderFilter() {
+ return new ForwardedHeaderFilter();
+}
+
+If you need to manually adjust the URL displayed in the Swagger UI, implement the ServerBaseUrlCustomizer
interface. This might be necessary to remove the port number, for example.
@Bean
+public class CustomServerBaseUrlCustomizer implements ServerBaseUrlCustomizer {
+ @Override
+ public String customize(String serverBaseUrl) {
+ try {
+ URL url = new URL(serverBaseUrl);
+ if (url.getHost().contains(".com")) {
+ serverBaseUrl = new URL(url.getProtocol(),url.getHost(),url.getFile()).toString();
+ }
+ } catch (MalformedURLException ex) {
+ // nothing we can do
+ }
+
+ return serverBaseUrl;
+ }
+}
+
+springdoc-openapi-starter-webmvc-ui
dependency breaks my public/index.html
welcome pageIf you already have static content on your root, and you don’t want it to be overridden by springdoc-openapi-starter-webmvc-ui
configuration, you can just define a custom configuration of the swagger-ui
, in order not to override the configuration of your files from in your context-root:
For example use:
+springdoc.swagger-ui.path= /swagger-ui/api-docs.html+
You can have a look on this sample test of the UI:
+ +You can write your own implementation of OpenApiCustomizer
.
An example is available on:
+ +@Bean
+public OpenApiCustomizer consumerTypeHeaderOpenAPICustomizer() {
+return openApi -> openApi.getPaths().values().stream().flatMap(pathItem -> pathItem.readOperations().stream())
+ .forEach(operation -> operation.addParametersItem(new HeaderParameter().$ref("#/components/parameters/myConsumerTypeHeader")));
+}
+
++ + | +
+This bean OpenApiCustomizer will be applied to the Default OpenAPI only.
+ |
+
If you need the OpenApiCustomizer
to applied to GroupedOpenApi
as well, then use GlobalOpenApiCustomizer
instead.
It is be possible to handle as return an empty content as response using, one of the following syntaxes:
+content = @Content
content = @Content(schema = @Schema(hidden = true))
For example:
+@Operation(summary = "Get thing", responses = {
+ @ApiResponse(description = "Successful Operation", responseCode = "200", content = @Content(mediaType = "application/json", schema = @Schema(implementation = String.class))),
+ @ApiResponse(responseCode = "404", description = "Not found", content = @Content),
+ @ApiResponse(responseCode = "401", description = "Authentication Failure", content = @Content(schema = @Schema(hidden = true))) })
+@RequestMapping(path = "/testme", method = RequestMethod.GET)
+ResponseEntity<String> testme() {
+ return ResponseEntity.ok("Hello");
+}
+
+An overloaded method on the same class, with the same HTTP Method and path, will have as a result, only one OpenAPI Operation generated.
+In addition, it’s recommended to have the @Operation
in the level of one of the overloaded methods. Otherwise it might be overridden if it’s declared many times within the same overloaded method.
You can use springdoc-openapi-maven-plugin
for this functionality:
You can customise the output directory (property outputDir): The default value is: ${project.build.directory}
+Principal
, Locale
, HttpServletRequest
and HttpServletResponse
and other injectable parameters supported by Spring MVC are excluded.
Full documentation here:
+ +If you don’t want to ignore the types Principal
, Locale
, HttpServletRequest
, and others,:
SpringDocUtils.getConfig().removeRequestWrapperToIgnore(HttpServletRequest.class)
+
+You should add the @SecurityRequirement
tags to your protected APIs.
For example:
+@Operation(security = { @SecurityRequirement(name = "bearer-key") })+
And the security definition sample:
+@Bean
+ public OpenAPI customOpenAPI() {
+ return new OpenAPI()
+ .components(new Components()
+ .addSecuritySchemes("bearer-key",
+ new SecurityScheme().type(SecurityScheme.Type.HTTP).scheme("bearer").bearerFormat("JWT")));
+}
+
+OAS 3 was released in July 2017, and there was no release of springfox
to support OAS 3.
+springfox
covers for the moment only swagger 2 integration with Spring Boot. The latest release date is June 2018. So, in terms of maintenance there is a big lack of support lately.
We decided to move forward and share the library that we already used on our internal projects, with the community.
+The biggest difference with springfox
, is that we integrate new features not covered by springfox
:
The integration between Spring Boot and OpenAPI 3 standard.
+We rely on on swagger-annotations
and swagger-ui
only official libraries.
We support new features on Spring 5, like spring-webflux
with annotated and functional style.
We do our best to answer all the questions and address all issues or enhancement requests
+There is no relation between springdoc-openapi
and springfox
.If you want to migrate to OpenAPI 3:
Remove all the dependencies and the related code to springfox
+Add springdoc-openapi-starter-webmvc-ui
dependency
If you don’t want to serve the UI from your root path or there is a conflict with an existing configuration, you can just change the following property:
+springdoc.swagger-ui.path=/you-path/swagger-ui.html+
You may have global parameters with Standard OpenAPI description.
+If you need the definitions to appear globally (within every group), no matter if the group fulfills the conditions specified on the GroupedOpenApi , you can use OpenAPI Bean.
+You can define common parameters under parameters in the global components section and reference them elsewhere via $ref
. You can also define global header parameters.
For this, you can override to OpenAPI Bean, and set the global headers or parameters definition on the components level.
+@Bean
+public OpenAPI customOpenAPI(@Value("${springdoc.version}") String appVersion) {
+ return new OpenAPI()
+ .components(new Components().addSecuritySchemes("basicScheme", new SecurityScheme().type(SecurityScheme.Type.HTTP).scheme("basic"))
+ .addParameters("myHeader1", new Parameter().in("header").schema(new StringSchema()).name("myHeader1")).addHeaders("myHeader2", new Header().description("myHeader2 header").schema(new StringSchema())))
+ .info(new Info()
+ .title("Petstore API")
+ .version(appVersion)
+ .description("This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters.")
+ .termsOfService("http://swagger.io/terms/")
+ .license(new License().name("Apache 2.0").url("http://springdoc.org")));
+}
+
+You can use: @SecurityScheme
annotation.
Or you can define it programmatically, by overriding OpenAPI Bean:
+ @Bean
+ public OpenAPI customOpenAPI(@Value("${springdoc.version}") String appVersion) {
+ return new OpenAPI()
+ .components(new Components().addSecuritySchemes("basicScheme",
+ new SecurityScheme().type(SecurityScheme.Type.HTTP).scheme("basic")))
+ info(new Info().title("SpringShop API").version(appVersion)
+ .license(new License().name("Apache 2.0").url("http://springdoc.org")));
+ }
+
+You can use @io.swagger.v3.oas.annotations.Hidden
annotation at @RestController
, @RestControllerAdvice
and method level
The @Hidden
annotation on exception handler methods, is considered when building generic (error) responses from @ControllerAdvice
exception handlers.
Or use: @Operation(hidden = true)
For global SecurityScheme, you can add it inside your own OpenAPI definition:
+@Bean
+public OpenAPI customOpenAPI() {
+ return new OpenAPI().components(new Components()
+ .addSecuritySchemes("basicScheme", new SecurityScheme()
+ .type(SecurityScheme.Type.HTTP).scheme("basic"))).info(new Info().title("Custom API")
+ .version("100")).addTagsItem(new Tag().name("mytag"));
+}
+
+The support of spring property resolver for @Info
: title
* description
* version
* termsOfService
The support of spring property resolver for @Info.license
: name
* url
The support of spring property resolver for @Info.contact
: name
* email
* url
The support of spring property resolver for @Operation
: description
* summary
The support of spring property resolver for @Parameter
: description
* name
The support of spring property resolver for @ApiResponse
: description
Its also possible to declare security URLs for @OAuthFlow
: openIdConnectUrl
* authorizationUrl
* refreshUrl
* tokenUrl
The support of spring property resolver for @Schema
: name
* title
* description
, by setting springdoc.api-docs.resolve-schema-properties
to true
The support of spring property resolver for @ExtensionProperty
by setting springdoc.api-docs.resolve-extensions-properties
to true
Generating automatically server URL may be useful, if the documentation is not present.
+If the server annotations are present, they will be used instead.
+By default, the OpenAPI description is calculated once, and then cached.
+Sometimes the same swagger-ui is served behind internal and external proxies. some users want the server URL, to be computed on each http request.
+In order to disable springdoc cache, you will have to set the following property:
+springdoc.cache.disabled= true+
swagger-ui
?You should use the springdoc-openapi-core
dependency only:
<dependency>
+ <groupId>org.springdoc</groupId>
+ <artifactId>springdoc-openapi-starter-webmvc-api</artifactId>
+ <version>latest.version</version>
+</dependency>
+springdoc-openapi
endpoints ?Use the following property:
+springdoc.api-docs.enabled=false+
To hide the response element, using @Schema
annotation, as follows, at operation level:
@Operation(responses = @ApiResponse(responseCode = "200", content = @Content(schema = @Schema(hidden = true))))+
Or directly at @ApiResponses
level:
@ApiResponses(value = {@ApiResponse(responseCode = "200", content = @Content(schema = @Schema(hidden = true))) }) +OR +@ApiResponse(responseCode = "404", description = "Not found", content = @Content)+
swagger-ui
, when I set a different context-path?If you use different context-path:
+server.servlet.context-path= /foo+
The swagger-ui
will be available on the following URL:
http://server:port/foo/swagger-ui.html
You can Define your own OpenAPI Bean: If you need the definitions to appear globally (within every group), no matter if the group fulfills the conditions specified on the GroupedOpenApi , you can use OpenAPI Bean.
+@Bean
+public OpenAPI customOpenAPI(@Value("${springdoc.version}") String appVersion) {
+ return new OpenAPI()
+ .components(new Components().addSecuritySchemes("basicScheme",
+ new SecurityScheme().type(SecurityScheme.Type.HTTP).scheme("basic")))
+ .info(new Info().title("SpringShop API").version(appVersion)
+ .license(new License().name("Apache 2.0").url("http://springdoc.org")));
+}
+
+If you need the definitions to appear within a specific group, and respect the conditions specified on the GroupedOpenApi, you can add OpenApiCustomizer to your GroupedOpenApi definition.
+GroupedOpenApi.builder().group("users").pathsToMatch(paths).packagesToScan(packagedToMatch).addOpenApiCustomizer(customerGlobalHeaderOpenApiCustomizer())
+ .build()
+
+@Bean
+public OpenApiCustomizer customerGlobalHeaderOpenApiCustomizer() {
+ return openApi -> openApi.path("/foo",
+ new PathItem().get(new Operation().operationId("foo").responses(new ApiResponses()
+ .addApiResponse("default",new ApiResponse().description("")
+ .content(new Content().addMediaType("fatz", new MediaType()))))));
+}
+
+The source code of the application is available at the following GitHub repository:
+ +The library supports the main file types: MultipartFile
, @RequestPart
, FilePart
You can upload a file as follows:
+@PostMapping(value = "/upload", consumes = {MediaType.MULTIPART_FORM_DATA_VALUE})
+public ResponseEntity<?> upload(@Parameter(description = "file") final MultipartFile file) {
+ return null;
+}
+
+@PostMapping(value = "/uploadFileWithQuery", consumes = {MediaType.MULTIPART_FORM_DATA_VALUE})
+public ResponseEntity<?> uploadFileWithQuery(@Parameter(description = "file") @RequestPart("file") final MultipartFile file,
+ @Parameter(description = "An extra query parameter") @RequestParam String name) {
+ return null;
+}
+
+@PostMapping(value = "/uploadFileWithJson", consumes = {MediaType.MULTIPART_FORM_DATA_VALUE}, produces = {
+ MediaType.APPLICATION_JSON_VALUE})
+public ResponseEntity<?> uploadFileWithJson(
+ @RequestBody(content = @Content(encoding = @Encoding(name = "jsonRequest", contentType = MediaType.APPLICATION_JSON_VALUE)))
+ @Parameter(description = "An extra JSON payload sent with file") @RequestPart("jsonRequest") final JsonRequest jsonRequest,
+ @RequestPart("file") final MultipartFile file) {
+ return null;
+}
+
+Any @GetMapping
parameters is marked as required, even if @RequestParam
is missing.
You can add @Parameter(required=false)
annotation if you need different behaviour.
Query parameters with defaultValue
specified are marked as required.
springdoc-openapi
renders these methods as a single endpoint. It detects the overloaded endpoints, and generates parameters.schema.oneOf.
With this property, all the springdoc-openapi
auto-configuration beans are disabled:
springdoc.api-docs.enabled=false+
Then enable the minimal Beans configuration, by adding this Bean:
+@Bean
+SpringDocConfiguration springDocConfiguration(){
+ return new SpringDocConfiguration();
+}
+
+@Bean
+SpringDocConfigProperties springDocConfigProperties() {
+ return new SpringDocConfigProperties();
+}
+
+@Bean
+ObjectMapperProvider objectMapperProvider(SpringDocConfigProperties springDocConfigProperties){
+ return new ObjectMapperProvider(springDocConfigProperties);
+}
+
+Then configure, the path of your custom UI yaml file.
+springdoc.swagger-ui.url=/api-docs.yaml+
The OpenAPI 3 specification does not allow explicitly adding Authorization header.
+Note: Header parameters named Accept, Content-Type and Authorization are not allowed. To describe these headers
For more information, you can read:
+ +This is the default behaviour if your @Controller
doesn’t have annotation @ResponseBody
You can change your controllers to @RestControllers
. Or add @ResponseBody
+ @Controller
.
If its not possible, you can configure springdoc to scan you additional controller using SpringDocUtils. For example:
+static {
+ SpringDocUtils.getConfig().addRestControllers(HelloController.class);
+}
+
+You can load groups dynamically using spring-boot configuration files.
+Note that, for this usage, you don’t have to declare the GroupedOpenApi Bean.
+You need to declare the following properties, under the prefix springdoc.group-configs.
+For example:
+springdoc.group-configs[0].group=users +springdoc.group-configs[0].paths-to-match=/user/** +springdoc.group-configs[0].packages-to-scan=test.org.springdoc.api+
The list of properties under this prefix, are available here:
+You can use springdoc annotation @ParameterObject.
+Request parameter annotated with @ParameterObject will help adding each field of the parameter as a separate request parameter.
+This is compatible with Spring MVC request parameters mapping to POJO object.
+This annotation does not support nested parameter objects.
+POJO object must contain getters for fields with mandatory prefix get
. Otherwise, the swagger documentation will not show the fields of the annotated entity.
springdoc-openapi
SNAPSHOT ?For testing purposes only, you can test temporarily using the last springdoc-openapi
SNAPSHOT
To achieve that, configure your pom.xml file with the following <repositories>
section:
<repositories>
+ <repository>
+ <name>Central Portal Snapshots</name>
+ <id>central-portal-snapshots</id>
+ <url>https://central.sonatype.com/repository/maven-snapshots/</url>
+ <releases>
+ <enabled>false</enabled>
+ </releases>
+ <snapshots>
+ <enabled>true</enabled>
+ </snapshots>
+ </repository>
+ </repositories>
+springdoc-openapi
MonetaryAmount support ?If an application wants to enable the springdoc-openapi
support, it declares:
SpringDocUtils.getConfig().replaceWithClass(MonetaryAmount.class, org.springdoc.core.converters.models.MonetaryAmount.class);
+
+Another solution, without using springdoc-openapi MonetaryAmount, would be:
+SpringDocUtils.getConfig().replaceWithSchema(MonetaryAmount.class, new ObjectSchema()
+ .addProperties("amount", new NumberSchema()).example(99.96)
+ .addProperties("currency", new StringSchema().example("USD")));
+
+The properties springdoc.swagger-ui.urls.*
, are suitable to configure external (/v3/api-docs url).
+For example if you want to agreagte all the endpoints of other services, inside one single application.
+IMPORTANT: Don’t forget that CORS needs to be enabled as well.
If your file open-api.json, contains the OpenAPI documentation in OpenAPI 3 format. +Then simply declare: The file name can be anything you want, from the moment your declaration is consistent yaml or json OpenAPI Spec.
+ springdoc.swagger-ui.url=/open-api.json
+Then the file open-api.json, should be located in: src/main/resources/static +No additional configuration is needed.
+If you are using standard headers.( For example using spring-security headers) +If the CSRF Token is required, swagger-ui automatically sends the new XSRF-TOKEN during each HTTP REQUEST.
+If your XSRF-TOKEN isn’t standards-based, you can use a requestInterceptor to manually capture and attach the latest xsrf token to requests programmatically via spring resource transformer:
+Starting from release v1.4.4 of springdoc-openapi, a new property is added to enable CSRF support, while using standard header names:
+springdoc.swagger-ui.csrf.enabled=true
+You can use the following property:
+springdoc.swagger-ui.disable-swagger-default-url=true
+Yes, you can use it in conjunction with @ParameterObject
annotation.
+Also, the spring-boot spring.data.web.
and spring.data.rest.default.
properties are supported since v1.4.5
You can use the following property:
+springdoc.show-login-endpoint=true
+You can use the following property:
+springdoc.remove-broken-reference-definitions=false
+The whole idea of springdoc-openapi
is to get your documentation the closest to the code, with minimal code changes.
+If the code contains @Deprecated
, sprindoc-openapi
will consider its schema as Deprecated as well.
+If you want to declare a field on swagger as non deprecated, even with the java code, the field contains @Depreacted
,
+You can use the following property that is available since release v1.4.3:
springdoc.model-converters.deprecating-converter.enabled=false
+You can use the following property:
+springdoc.model-and-view-allowed=true
+You can use the following property:
+springdoc.writer-with-default-pretty-printer=true
+Complex objects are always resolved as a reference to a schema defined in components.
+For example let’s consider a Instance
class with an workAddress
and homeAddress
attribute of type Address
:
public class PersonDTO {
+
+ @JsonProperty
+ private String email;
+
+ @JsonProperty
+ private String firstName;
+
+ @JsonProperty
+ private String lastName;
+
+ @Schema(ref = "WorkAddressSchema")
+ @JsonProperty
+ private Address workAddress;
+
+ @Schema(ref = "HomeAddressSchema")
+ @JsonProperty
+ private Address homeAddress;
+
+}
+
+public class Address {
+
+ @JsonProperty
+ private String addressName;
+
+}
+
+If you want to define two different schemas for this class, you can set up 2 different schemas as follow:
+@Bean
+public OpenAPI customOpenAPI() {
+return new OpenAPI().components(new Components()
+.addSchemas("WorkAddressSchema", getSchemaWithDifferentDescription(Address.class, "work Address" ))
+.addSchemas("HomeAddressSchema", getSchemaWithDifferentDescription(Address.class, "home Address" )));
+}
+
+private Schema getSchemaWithDifferentDescription(Class className, String description){
+ResolvedSchema resolvedSchema = ModelConverters.getInstance()
+.resolveAsResolvedSchema(
+new AnnotatedType(className).resolveAsRef(false));
+return resolvedSchema.schema.description(description);
+}
+
+For example let’s consider a Instance
class with an email
attribute:
public class PersonDTO {
+
+ @JsonProperty
+ private String email;
+
+ @JsonProperty
+ private String firstName;
+
+ @JsonProperty
+ private String lastName;
+
+
+}
+
+If you want to define two different description for the email
, you can set up 2 different schemas as follow:
@Bean
+public OpenAPI customOpenAPI() {
+return new OpenAPI().components(new Components()
+.addSchemas("PersonDTO1", getFieldSchemaWithDifferentDescription(PersonDTO.class, "work email" ))
+.addSchemas("PersonDTO2", getFieldSchemaWithDifferentDescription(PersonDTO.class, "home email" )));
+}
+
+private Schema getFieldSchemaWithDifferentDescription(Class className, String description){
+ ResolvedSchema resolvedSchema = ModelConverters.getInstance()
+ .resolveAsResolvedSchema(
+ new AnnotatedType(className).resolveAsRef(false));
+ return resolvedSchema.schema.addProperties("email", new StringSchema().description(description));
+}
+
+You can customize swagger documentation static resources located in META-INF/resources/webjars/swagger-ui/{swagger.version}/
. The list of resources includes:
index.html
swagger-ui-bundle.js
swagger-ui.css
swagger-ui-standalone-preset.js
swagger-ui.css.map
swagger-ui-bundle.js.map
swagger-ui-standalone-preset.js.map
favicon-32x32.png
To do this, you need to extend the implementation of SwaggerIndexPageTransformer
public class SwaggerCodeBlockTransformer
+ extends SwaggerIndexPageTransformer {
+ // < constructor >
+ @Override
+ public Resource transform(HttpServletRequest request,
+ Resource resource,
+ ResourceTransformerChain transformer)
+ throws IOException {
+ if (resource.toString().contains("swagger-ui.css")) {
+ final InputStream is = resource.getInputStream();
+ final InputStreamReader isr = new InputStreamReader(is);
+ try (BufferedReader br = new BufferedReader(isr)) {
+ final String css = br.lines().collect(Collectors.joining());
+ final byte[] transformedContent = css.replace("old", "new").getBytes();
+ return new TransformedResource(resource, transformedContent);
+ } // AutoCloseable br > isr > is
+ }
+ return super.transform(request, resource, transformer);
+ }
+
+}
+
+Next, add transformer @Bean
to your @Configuration
@Configuration
+public class OpenApiConfig {
+ @Bean
+ public SwaggerIndexTransformer swaggerIndexTransformer(
+ SwaggerUiConfigProperties a,
+ SwaggerUiOAuthProperties b,
+ SwaggerUiConfigParameters c,
+ SwaggerWelcomeCommon d) {
+ return new SwaggerCodeBlockTransformer(a, b, c, d);
+ }
+}
+
+Illustrative example
+The native support available added in spring-boot 3. +If you have some time, do not hesitate to test it before the next release.
+For the OpenAPI REST endpoints, you just need to build your application with the spring native
profile.
If you give @OpenAPIDefinition
or @SecurityScheme
to a class that has no implementation, that class will disappear when you natively compile.
+To avoid this, give the class a @Configuration
.
@Configuration +@OpenAPIDefinition(info = @Info(title = "My App", description = "description")) +public class OpenAPIConfig { +}+
When your application is using spring without (spring-boot), you need to add beans and auto-configuration that are natively provided in spring-boot.
+For example, lets assume you want load the swagger-ui in spring-mvc application:
+You mainly, need to add the springdoc-openapi module
+<dependency>
+ <groupId>org.springdoc</groupId>
+ <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
+ <version>last.version</version>
+</dependency>
+If you don’t have the spring-boot and spring-boot-autoconfigure dependencies, you need to add them. And pay attention to the compatibility matrix, between you spring.version and spring-boot.version. For example, in this case (spring.version=5.1.12.RELEASE):
+ <dependency>
+ <groupId>org.springframework.boot</groupId>
+ <artifactId>spring-boot-autoconfigure</artifactId>
+ <version>3.3.3</version>
+ </dependency>
+Scan for the springdoc-openapi
'auto-configuration classes that spring-boot automatically loads for you.
Depending on your module, you can find them on the file: spring.factories
of each springdoc-openapi
module.
@Configuration
+@EnableWebMvc
+public class WebConfig implements WebApplicationInitializer {
+
+ @Override
+ public void onStartup(ServletContext servletContext) {
+ WebApplicationContext context = getContext();
+ servletContext.addListener(new ContextLoaderListener(context));
+ ServletRegistration.Dynamic dispatcher = servletContext.addServlet("RestServlet",
+ new DispatcherServlet(context));
+ dispatcher.setLoadOnStartup(1);
+ dispatcher.addMapping("/*");
+ }
+
+ private AnnotationConfigWebApplicationContext getContext() {
+ AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
+ context.register(this.getClass(),
+ SpringDocConfiguration.class,
+ SpringDocConfigProperties.class,
+ SpringDocSpecPropertiesConfiguration.class,
+ SpringDocWebMvcConfiguration.class,
+ MultipleOpenApiSupportConfiguration.class,
+ SwaggerConfig.class,
+ SwaggerUiConfigProperties.class,
+ SwaggerUiOAuthProperties.class,
+ );
+ return context;
+ }
+}
+
+Depending on your module, you can find them on the file: org.springframework.boot.autoconfigure.AutoConfiguration.imports
of each springdoc-openapi
module.
For groups usage make sure your GroupedOpenApi
Beans are scanned.
If additionally, you are using custom context path
: /my-servlet-path
. Make sure you declare the following property:
spring.mvc.servlet.path=/my-servlet-path+
springdoc-openapi
with spring-boot
?springdoc-openapi 3.x
is compatible with spring-boot 4
.
In general, you should only pick the last stable version as per today 3.0.0-M1.
+More precisely, this the exhaustive list of spring-boot versions against which springdoc-openapi
has been built:
Spring Boot Versions |
+Springdoc OpenAPI Versions |
+
|
+
|
+
Swagger UI unable to render definition
, when overriding the default spring registered HttpMessageConverter
?When overriding the default spring-boot registered HttpMessageConverter
, you should have ByteArrayHttpMessageConverter
registered as well to have proper springdoc-openapi
support.
converters.add(new ByteArrayHttpMessageConverter());
+ converters.add(new MappingJackson2HttpMessageConverter(jacksonBuilder.build()));
+
++ + | +
+Order is very important, when registering HttpMessageConverters .
+ |
+
The issue is caused by the changes introduced by Spring-Boot 3.2.0
+in particular for the Parameter Name Discovery.
+This can be fixed by adding the -parameters
arg to the Maven Compiler Plugin.
<plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-compiler-plugin</artifactId>
+ <configuration>
+ <parameters>true</parameters>
+ </configuration>
+</plugin>
+springdoc-openapi
java library helps to automate the generation of API documentation using spring boot projects.
+springdoc-openapi
works by examining an application at runtime to infer API semantics based on spring configurations, class structure and various annotations.
Automatically generates documentation in JSON/YAML and HTML format APIs. +This documentation can be completed by comments using swagger-api annotations.
+This library supports:
+OpenAPI 3
+Spring-boot v4 (Java 17 & Jakarta EE 9)
+JSR-303, specifically for @NotNull, @Min, @Max, and @Size.
+Swagger-ui
+OAuth 2
+GraalVM native images
+The following video introduces the Library:
+This is a community-based project, not maintained by the Spring Framework Contributors (Pivotal).
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+