添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
相关文章推荐
英勇无比的仙人掌  ·  AttributeError: Api ...·  2 天前    · 
健身的显示器  ·  什么是 Swagger?- ...·  1 周前    · 
兴奋的开水瓶  ·  springdoc-openapi v1.8.0·  3 周前    · 
害羞的大象  ·  ASP.NETCoreWebAPI-在Cor ...·  4 月前    · 
英勇无比的双杠  ·  DateFormat | ...·  4 月前    · 
爱跑步的口罩  ·  Sony WI-C100 vs Sony ...·  1 周前    · 
讲道义的青蛙  ·  Página inicial | ...·  2 月前    · 
  • 4.1. Adding API Information and Security documentation
  • 4.2. Error Handling for REST using @ControllerAdvice
  • 4.3. Disabling the springdoc-openapi endpoints
  • 4.4. Disabling the swagger-ui
  • 4.5. Swagger-ui configuration
  • 4.6. Selecting the Rest Controllers to include in the documentation
  • 4.7. Spring-webflux/WebMvc.fn with Functional Endpoints
  • 4.8. Integration with WildFly
  • 5. Springdoc-openapi Properties
  • 5.1. springdoc-openapi core properties
  • 5.2. swagger-ui properties
  • 6. Springdoc-openapi Plugins
  • 6.1. Maven plugin
  • 6.2. Gradle plugin
  • 7. Springdoc-openapi Demos
  • 7.1. springdoc applications demos
  • 7.2. Source code of the Demo Applications
  • 8. Migrating from SpringFox
  • 9. Other resources
  • 9.1. Additional resources to get started
  • 9.2. Dependencies repository
  • 10. Sponsor
  • 10.1. Benefits of being a bronze sponsor
  • 10.2. Benefits of being a silver sponsor
  • 10.3. Benefits of being a gold sponsor
  • 11. Special Thanks
  • 12. F.A.Q
  • 12.1. How can I define multiple OpenAPI definitions in one Spring Boot project?
  • 12.2. How can I configure Swagger UI?
  • 12.3. How can I filter the resources documented in the output specification by the provided group?
  • 12.4. How can I disable/enable Swagger UI generation based on env variable?
  • 12.5. How can I control the default expansion setting for the operations and tags, in the Swagger UI,
  • 12.6. How can I change the layout of the swagger-ui ?
  • 12.7. How can I sort endpoints alphabetically?
  • 12.8. How can I disable the try it out button?
  • 12.9. How can I add Reusable Enums?
  • 12.10. How can i apply enumAsRef = true to all enums?
  • 12.11. How can I explicitly set which paths to filter?
  • 12.12. How can I explicitly set which packages to scan?
  • 12.13. How can I set Swagger properties programmatically?
  • 12.14. How can I ignore some field of model?
  • 12.15. How can I ignore @AuthenticationPrincipal parameter from spring-security?
  • 12.16. Is there a Gradle plugin available?
  • 12.17. How can I hide a parameter from the documentation?
  • 12.18. Is @Parameters annotation supported?
  • 12.19. Does springdoc-openapi support Jersey?
  • 12.20. Can springdoc-openapi generate API only for @RestController ?
  • 12.21. Are the following validation annotations supported : @NotEmpty @NotBlank @PositiveOrZero @NegativeOrZero ?
  • 12.22. How can I map Pageable (spring-data-commons) object to correct URL-Parameter in Swagger UI?
  • 12.23. How can I generate enums in the generated description?
  • 12.24. How can I deploy springdoc-openapi-ui behind a reverse proxy?
  • 12.25. Is @JsonView annotations in Spring MVC APIs supported?
  • 12.26. Adding springdoc-openapi-ui dependency breaks my public/index.html welcome page
  • 12.27. How can I test the Swagger UI?
  • 12.28. How can I customise the OpenAPI object?
  • 12.29. How can I return an empty content as response?
  • 12.30. How are endpoints with multiple consuming media types supported?
  • 12.31. How can I get yaml and json (OpenAPI) in compile time?
  • 12.32. What are the ignored types in the documentation?
  • 12.33. How can i disable ignored types:
  • 12.34. How do I add authorization header in requests?
  • 12.35. Differentiation to Springfox project
  • 12.36. How do I migrate to OpenAPI 3 with springdoc-openapi
  • 12.37. How can I set a global header?
  • 12.38. Are Callbacks supported?
  • 12.39. How can I define SecurityScheme?
  • 12.40. How can I hide an operation or a controller from documentation?
  • 12.41. How to configure global security schemes?
  • 12.42. Can I use spring property with swagger annotations?
  • 12.43. How is server URL generated?
  • 12.44. How can I disable springdoc-openapi cache?
  • 12.45. How can I expose the mvc api-docs endpoints without using the swagger-ui ?
  • 12.46. How can I disable springdoc-openapi endpoints?
  • 12.47. How can I hide Schema of the the response?
  • 12.48. What is the URL of the swagger-ui , when I set a different context-path?
  • 12.49. Can I customize OpenAPI object programmatically?
  • 12.50. Where can I find the source code of the demo applications?
  • 12.51. Does this library supports annotations from interfaces?
  • 12.52. What is the list of the excluded parameter types?
  • 12.53. Is file upload supported?
  • 12.54. Can I use @Parameter inside @Operation annotation?
  • 12.55. Why my parameter is marked as required?
  • 12.56. How are overloaded methods with the same endpoints, but with different parameters
  • 12.57. What is a proper way to set up Swagger UI to use provided spec.yml?
  • 12.58. Is there a way to send authorization header through the @Parameter tag?
  • 12.59. My Rest Controller using @Controller annotation is ignored?
  • 12.60. How can I define groups using application.yml?
  • 12.61. How can I extract fields from parameter object?
  • 12.62. How to Integrate Open API 3 with Spring project (not Spring Boot)?
  • 12.63. How can I use the last springdoc-openapi SNAPSHOT ?
  • 12.64. How can I use enable springdoc-openapi MonetaryAmount support?
  • 12.65. How can i aggregate external endpoints (exposing OPENAPI 3 spec) inside one single application?
  • 12.66. How can use custom json/yml file instead of generated one?
  • 12.67. How can i enable CSRF support?
  • 12.68. How can i disable the default swagger petstore URL?
  • 12.69. Is @PageableDefault supported, to enhance the OpenAPI 3 documentation?
  • 12.70. How can I make spring security login-endpoint visible?
  • 12.71. How can I show schema definitions even if the schema is not referenced?
  • 12.72. How to override @Deprecated?
  • 12.73. How can i display a method that returns ModelAndView?
  • 12.74. How can i have pretty-printed output of the OpenApi specification?
  • 12.75. How can i define different schemas for the same class?
  • 12.76. How can i define different description for a class attribute depending on usage?
  • 12.77. Customizing swagger static resources
  • 12.78. What is the compatibility matrix of springdoc-openapi with spring-boot ?
  • 12.79. Why am i getting an error: 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:

    <groupId>org.springdoc</groupId> <artifactId>springdoc-openapi-ui</artifactId> <version>1.8.0</version> </dependency>

    This will automatically deploy swagger-ui to a spring-boot 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-webmvc-core</artifactId>
          <version>1.8.0</version>
       </dependency>

    Documentation can 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-webflux-ui</artifactId>
          <version>1.8.0</version>
       </dependency>

    3.4. Spring Hateoas support

    The support for Spring Hateoas is available using the dependency springdoc-openapi-hateoas. The projects that use Spring Hateoas should combine this dependency with the springdoc-openapi-ui dependency. This dependency enables the support of Spring Hateoas format.

       <dependency>
          <groupId>org.springdoc</groupId>
          <artifactId>springdoc-openapi-hateoas</artifactId>
          <version>1.8.0</version>
       </dependency>

    3.5. Spring Data Rest support

    The projects that use spring-data-rest can add the following dependency in combination with the springdoc-openapi-ui dependency. This dependency enables the support of spring-boot-starter-data-rest types like: @RepositoryRestResource and QuerydslPredicate annotations.

       <dependency>
          <groupId>org.springdoc</groupId>
          <artifactId>springdoc-openapi-data-rest</artifactId>
          <version>1.8.0</version>
       </dependency>

    3.6. Spring Security support

    For a project that uses spring-security, you should add the following dependency, in combination with the springdoc-openapi-ui dependency: This dependency helps ignoring @AuthenticationPrincipal in case its used on REST Controllers.

       <dependency>
          <groupId>org.springdoc</groupId>
          <artifactId>springdoc-openapi-security</artifactId>
          <version>1.8.0</version>
       </dependency>
    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:

    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:

    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.

    3.8. Spring Cloud Function Web support

    spring-cloud-function-web exposes Java Function as REST endpoint automatically. * Since version v1.6.3 , the support of functional endpoints has been added.

    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

    @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());
    

    3.9. Kotlin support

    For a project that uses Kotlin, you should add the following dependency. This dependency improves the support of Kotlin types:

       <dependency>
          <groupId>org.springdoc</groupId>
          <artifactId>springdoc-openapi-kotlin</artifactId>
          <version>1.8.0</version>
       </dependency>

    If you are using spring-web, you should combine the springdoc-openapi-kotlin module with springdoc-openapi-ui.

    If you are using spring-webflux, you should combine the springdoc-openapi-kotlin module with springdoc-openapi-webflux-ui.

    3.10. Groovy support

    For a project that uses Groovy, you should add the following dependency, in combination with the springdoc-openapi-ui dependency: This dependency improves the support of Kotlin types:

       <dependency>
          <groupId>org.springdoc</groupId>
          <artifactId>springdoc-openapi-groovy</artifactId>
          <version>1.8.0</version>
       </dependency>
    <groupId>org.springdoc</groupId> <artifactId>springdoc-openapi-javadoc</artifactId> <version>1.8.0</version> </dependency>

    This dependency improves the support of javadoc tags and comments:

    <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <annotationProcessorPaths> <groupId>com.github.therapi</groupId> <artifactId>therapi-runtime-javadoc-scribe</artifactId> <version>0.15.0</version> </path> </annotationProcessorPaths> </configuration> </plugin> </plugins> </build>

    4.1. Adding API Information and Security documentation

    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.

    4.2. Error Handling for REST using @ControllerAdvice

    To generate documentation automatically, make sure all the methods declare the HTTP Code responses using the annotation: @ResponseStatus

    4.3. Disabling the springdoc-openapi endpoints

    In 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

    4.6. Selecting the Rest Controllers to include in the documentation

    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/**

    4.7. Spring-webflux/WebMvc.fn with Functional Endpoints

    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();
    

    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));
    
    @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:

    <groupId>org.webjars</groupId> <artifactId>webjars-locator-jboss-vfs</artifactId> <version>0.1.0</version> </dependency>

    springdoc-openapi relies on standard spring configuration properties (yml or properties) using the standard files locations.

    5.1. springdoc-openapi core properties

    springdoc.api-docs.path

    /v3/api-docs

    String, For custom path of the OpenAPI documentation in Json format.

    springdoc.api-docs.enabled

    Boolean. To disable the springdoc-openapi endpoint (/v3/api-docs by default).

    springdoc.packages-to-scan

    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)

    springdoc.produces-to-match

    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)

    springdoc.consumes-to-match

    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)

    springdoc.packages-to-exclude

    List of Strings.The list of packages to exclude (comma separated)

    springdoc.default-consumes-media-type

    application/json

    String. The default consumes media type.

    springdoc.default-produces-media-type

    String.The default produces media type.

    springdoc.cache.disabled

    false

    Boolean. To disable the springdoc-openapi cache of the calculated OpenAPI.

    springdoc.show-actuator

    false

    Boolean. To display the actuator endpoints.

    springdoc.auto-tag-classes

    Boolean. To disable the springdoc-openapi automatic tags.

    springdoc.model-and-view-allowed

    false

    Boolean. To allow RestControllers with ModelAndView return to appear in the OpenAPI description.

    springdoc.override-with-generic-response

    Boolean. When true, automatically adds @ControllerAdvice responses to all the generated responses.

    springdoc.api-docs.groups.enabled

    Boolean. To disable the springdoc-openapi groups.

    springdoc.group-configs[0].group

    String.The group name

    springdoc.group-configs[0].display-name

    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)

    springdoc.group-configs[0].paths-to-match

    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)

    springdoc.group-configs[0].packages-to-exclude

    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)

    springdoc.group-configs[0].consumes-to-match

    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)

    springdoc.webjars.prefix

    /webjars

    String, To change the webjars prefix that is visible the URL of swagger-ui for spring-webflux.

    springdoc.api-docs.resolve-schema-properties

    false

    Boolean. To enable property resolver on @Schema (name, title and description).

    springdoc.remove-broken-reference-definitions

    Boolean. To disable removal of broken reference definitions.

    springdoc.writer-with-default-pretty-printer

    false

    Boolean. To enable pretty print of the OpenApi specification.

    springdoc.model-converters.deprecating-converter.enabled

    Boolean. To disable deprecating model converter.

    springdoc.model-converters.polymorphic-converter.enabled

    Boolean. To disable polymorphic model converter.

    springdoc.model-converters.pageable-converter.enabled

    Boolean. To disable pageable model converter.

    springdoc.model-converters.sort-converter.enabled

    Boolean. To disable Sort converter.

    springdoc.use-fqn

    false

    Boolean. To enable fully qualified names.

    springdoc.show-login-endpoint

    false

    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.

    springdoc.writer-with-order-by-keys

    false

    Boolean. Enable a deterministic/alphabetical ordering.

    springdoc.use-management-port

    false

    Boolean. To expose the swagger-ui on the actuator management port.

    springdoc.disable-i18n

    false

    Boolean. To disable automatic translation using i18n.

    springdoc.show-spring-cloud-functions

    Boolean. To display the spring-cloud-function web endpoints.

    springdoc.api-docs.version

    openapi_3_0

    String. To Choose OpenAPI 3.0 or OpenAPI 3.1 (using the value OPENAPI_3_1).

    springdoc.default-flat-param-object

    false

    Boolean. To default flatten parameter.

    springdoc.default-support-form-data

    false

    Boolean. To default set parameters to form data when specifying api to accept form data.

    springdoc.nullable-request-parameter-enabled

    Boolean. To default Enable Support for nullable request parameters in Kotlin.

    springdoc.show-oauth2-endpoints

    false

    Boolean. To make spring security oauth2-endpoint visible.

    springdoc.api-docs.resolve-extensions-properties

    false

    Boolean. To enable support of spring property resolver for @ExtensionProperty.

    springdoc.enable-default-api-docs

    Boolean. To enable default OpenAPI endpoint /v3/api-docs.

    springdoc.trim-kotlin-indent

    false

    Boolean. Adjust indentation when parsing the @Operation annotation in Kotlin.

    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.

    springdoc.swagger-ui.path

    /swagger-ui.html

    String, For custom path of the swagger-ui HTML documentation.

    springdoc.swagger-ui.enabled

    Boolean. To disable the swagger-ui endpoint (/swagger-ui.html by default).

    springdoc.swagger-ui.configUrl

    /v3/api-docs/swagger-config

    String. URL to fetch external configuration document from.

    springdoc.swagger-ui.layout

    BaseLayout

    String. The name of a component available via the plugin system to use as the top-level layout for Swagger UI.

    springdoc.swagger-ui.validatorUrl

    validator.swagger.io/validator

    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.

    springdoc.swagger-ui.tryItOutEnabled

    false

    Boolean. Controls whether the "Try it out" section should be enabled by default.

    springdoc.swagger-ui.filter

    false

    Boolean OR String. If set, enables filtering. The top bar will show an edit box that you can use to filter the tagged operations that are shown. Can be Boolean to enable or disable, or a string, in which case filtering will be enabled using that string as the filter expression. Filtering is case sensitive matching the filter expression anywhere inside the tag.

    springdoc.swagger-ui.operationsSorter

    Function=(a ⇒ a). Apply a sort to the operation list of each API. It can be 'alpha' (sort by paths alphanumerically), 'method' (sort by HTTP method) or a function (see Array.prototype.sort() to know how sort function works). Default is the order returned by the server unchanged.

    springdoc.swagger-ui.tagsSorter

    Function=(a ⇒ a). Apply a sort to the tag list of each API. It can be 'alpha' (sort by paths alphanumerically) or a function see Array.prototype.sort() to learn how to write a sort function). Two tag name strings are passed to the sorter for each pass. Default is the order determined by Swagger UI.

    springdoc.swagger-ui.oauth2RedirectUrl

    /swagger-ui/oauth2-redirect.html

    String. OAuth redirect URL.

    springdoc.swagger-ui.displayOperationId

    false

    Boolean. Controls the display of operationId in operations list. The default is false.

    springdoc.swagger-ui.displayRequestDuration

    false

    Boolean. Controls the display of the request duration (in milliseconds) for "Try it out" requests.

    springdoc.swagger-ui.deepLinking

    false

    Boolean. If set to true, enables deep linking for tags and operations. See the [Deep Linking documentation](swagger.io/docs/open-source-tools/swagger-ui/usage/deep-linking) for more information.

    springdoc.swagger-ui.defaultModelsExpandDepth

    Number. The default expansion depth for models (set to -1 completely hide the models).

    springdoc.swagger-ui.defaultModelExpandDepth

    Number. The default expansion depth for the model on the model-example section.

    springdoc.swagger-ui.defaultModelRendering

    String=["example"*, "model"]. Controls how the model is shown when the API is first rendered. (The user can always switch the rendering for a given model by clicking the 'Model' and 'Example Value' links.)

    springdoc.swagger-ui.docExpansion

    String=["list"*, "full", "none"]. Controls the default expansion setting for the operations and tags. It can be 'list' (expands only the tags), 'full' (expands the tags and operations) or 'none' (expands nothing).

    springdoc.swagger-ui.maxDisplayedTags

    Number. If set, limits the number of tagged operations displayed to at most this many. The default is to show all operations.

    springdoc.swagger-ui.showExtensions

    false

    Boolean. Controls the display of vendor extension (x-) fields and values for Operations, Parameters, and Schema.

    springdoc.swagger-ui.url

    String.To configure, the path of a custom OpenAPI file . Will be ignored if urls is used.

    springdoc.swagger-ui.showCommonExtensions

    false

    Boolean. Controls the display of extensions (pattern, maxLength, minLength, maximum, minimum) fields and values for Parameters.

    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.

    springdoc.swagger-ui.queryConfigEnabled

    false

    Boolean. Disabled since v1.6.0. This parameter enables (legacy) overriding configuration parameters via URL search params. See security advisory before enabling this feature.

    springdoc.swagger-ui.oauth. additionalQueryStringParams

    String. Additional query parameters added to authorizationUrl and tokenUrl.

    springdoc.swagger-ui.disable-swagger-default-url

    false

    Boolean. To disable the swagger-ui default petstore url. (Available since v1.4.1).

    springdoc.swagger-ui.urls[0].url

    URL. The url of the swagger group, used by Topbar plugin. URLs must be unique among all items in this array, since they’re used as identifiers.

    springdoc.swagger-ui.urls[0].name

    String. The name of the swagger group, used by Topbar plugin. Names must be unique among all items in this array, since they’re used as identifiers.

    springdoc.swagger-ui.urlsPrimaryName

    String. The name of the swagger group which will be displayed when Swagger UI loads.

    springdoc.swagger-ui.oauth.clientId

    String. Default clientId. MUST be a string.

    springdoc.swagger-ui.oauth.clientSecret

    String. Default clientSecret. Never use this parameter in your production environment. It exposes crucial security information. This feature is intended for dev/test environments only.

    springdoc.swagger-ui.oauth.realm

    String. realm query parameter (for OAuth 1) added to authorizationUrl and tokenUrl.

    springdoc.swagger-ui.oauth.appName

    String. OAuth application name, displayed in authorization popup.

    springdoc.swagger-ui.oauth.scopeSeparator

    String. OAuth scope separator for passing scopes, encoded before calling, default value is a space (encoded value %20).

    springdoc.swagger-ui.csrf.enabled

    false

    Boolean. To enable CSRF support

    springdoc.swagger-ui.csrf.use-local-storage

    false

    Boolean. To get the CSRF token from the Local Storage.

    springdoc.swagger-ui.csrf.use-session-storage

    false

    Boolean. To get the CSRF token from the Session Storage.

    springdoc.swagger-ui.csrf.cookie-name

    XSRF-TOKEN

    String. Optional CSRF, to set the CSRF cookie name.

    springdoc.swagger-ui.csrf.header-name

    X-XSRF-TOKEN

    String. Optional CSRF, to set the CSRF header name.

    springdoc.swagger-ui.syntaxHighlight.activated

    Boolean. Whether syntax highlighting should be activated or not.

    springdoc.swagger-ui.syntaxHighlight.theme

    agate

    String. String=["agate"*, "arta", "monokai", "nord", "obsidian", "tomorrow-night"]. Highlight.js syntax coloring theme to use. (Only these 6 styles are available.)

    springdoc.swagger-ui.oauth. useBasicAuthentication WithAccessCodeGrant

    false

    Boolean. Only activated for the accessCode flow. During the authorization_code request to the tokenUrl, pass the Client Password using the HTTP Basic Authentication scheme (Authorization header with Basic base64encode(client_id + client_secret)).

    springdoc.swagger-ui.oauth. usePkceWithAuthorization CodeGrant

    false

    Boolean.Only applies to authorizatonCode flows. Proof Key for Code Exchange brings enhanced security for OAuth public clients.

    springdoc.swagger-ui.persistAuthorization

    false

    Boolean. If set to true, it persists authorization data and it would not be lost on browser close/refresh

    springdoc.swagger-ui.use-root-path

    false

    Boolean. If set to true, the swagger-ui will be accessible from the application root path directly.

    6.1. Maven plugin

    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.4</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:

    plugins {
          id("org.springframework.boot") version "2.7.0"
          id("org.springdoc.openapi-gradle-plugin") version "1.9.0"
          <groupId>org.springdoc</groupId>
          <artifactId>springdoc-openapi-ui</artifactId>
          <version>1.8.0</version>
       </dependency>

    Replace swagger 2 annotations with swagger 3 annotations (it is already included with springdoc-openapi-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(hidden = true)@Schema(accessMode = READ_ONLY)

    @ApiModelProperty@Schema

    @ApiOperation(value = "foo", notes = "bar")@Operation(summary = "foo", description = "bar")

    @ApiParam@Parameter

    @ApiResponse(code = 404, message = "foo")@ApiResponse(responseCode = "404", description = "foo")

    If you’re using an object to capture multiple request query params, annotation that method argument with @ParameterObject

    This step is optional: Only if you have multiple Docket beans replace them with GroupedOpenApi beans.

    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()); 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(); 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"));

    9.2. Dependencies repository

    The springdoc-openapi libraries are hosted on maven central repository. The artifacts can be viewed accessed at the following locations:

    Releases:

    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!

    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'.

    12.1. How can I define multiple OpenAPI definitions in one Spring Boot 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:

    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();
    
    @Bean
    public GroupedOpenApi userOpenApi() {
       String packagesToscan[] = {"test.org.springdoc.api.app68.api.user"};
       return GroupedOpenApi.builder().group("users").packagesToScan(packagesToscan)
             .build();
    public GroupedOpenApi petOpenApi() {
       String paths[] = {"/pet/**"};
       return GroupedOpenApi.builder().group("pets").pathsToMatch(paths)
             .build();
    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();
    

    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.

    #For sorting endpoints alphabetically
    springdoc.swagger-ui.operationsSorter=alpha
    #For sorting tags alphabetically
    springdoc.swagger-ui.tagsSorter=alpha
    @Bean @Primary fun swaggerUiConfig(config: SwaggerUiConfigProperties): SwaggerUiConfigProperties { config.showCommonExtensions = true config.queryConfigEnabled = true return config
    <dependency>
       <groupId>org.springdoc</groupId>
       <artifactId>springdoc-openapi-security</artifactId>
       <version>last.version</version>
    </dependency>

    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:

    https://github.com/swagger-api/swagger-samples/tree/2.0/java/java-jersey2-minimal

    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.

    12.22. How can I map 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:

    static {
        getConfig().replaceParameterObjectWithClass(org.springframework.data.domain.Pageable.class, Pageable.class)
                .replaceParameterObjectWithClass(org.springframework.data.domain.PageRequest.class, Pageable.class);
    

    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, …​

    @GetMapping("/example")
    public Object example(@Parameter(name = "json", schema = @Schema(description = "var 1", type = "string", allowableValues = {"1", "2"}))
    String json) {
       return null;
    

    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:

    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:

    If you already have static content on your root, and you don’t want it to be overridden by springdoc-openapi-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:

    @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")));
    

    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.

    Principal, Locale, HttpServletRequest and HttpServletResponse and other injectable parameters supported by Spring MVC are excluded.

    Full documentation here:

    https://docs.spring.io/spring/docs/5.1.x/spring-framework-reference/web.html#mvc-ann-arguments

    .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-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:

    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")));
    
    @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)

    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

    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:

    <dependency>
      <groupId>org.springdoc</groupId>
      <artifactId>springdoc-openapi-webmvc-core</artifactId>
      <version>latest.version</version>
    </dependency>
    @ApiResponses(value = {@ApiResponse(responseCode = "200", content = @Content(schema = @Schema(hidden = true))) })
    @ApiResponse(responseCode = "404", description = "Not found", content = @Content)
    @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")));
    
    GroupedOpenApi.builder().group("users").pathsToMatch(paths).packagesToScan(packagedToMatch).addOpenApiCustomiser(customerGlobalHeaderOpenApiCustomiser())
                    .build()
    @Bean
    public OpenApiCustomiser customerGlobalHeaderOpenApiCustomiser() {
        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()))))));
    
    @Bean
    SpringDocConfiguration springDocConfiguration(){
       return new SpringDocConfiguration();
    @Bean
    SpringDocConfigProperties springDocConfigProperties() {
       return new SpringDocConfigProperties();
    @Bean
    ObjectMapperProvider objectMapperProvider(SpringDocConfigProperties springDocConfigProperties){
        return new ObjectMapperProvider(springDocConfigProperties);
    @Bean
    SpringDocUIConfiguration SpringDocUIConfiguration(Optional<SwaggerUiConfigProperties> optionalSwaggerUiConfigProperties){
        return new SpringDocUIConfiguration(optionalSwaggerUiConfigProperties);
    

    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:

    https://swagger.io/docs/specification/describing-parameters/#header-parameters

    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:

    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.

    12.62. How to Integrate Open API 3 with Spring project (not 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:

    <groupId>org.springdoc</groupId> <artifactId>springdoc-openapi-ui</artifactId> <version>last.version</version> </dependency>
    <groupId>org.springframework.boot</groupId> <artifactId>spring-boot</artifactId> <version>2.1.11.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-autoconfigure</artifactId> <version>2.1.11.RELEASE</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.

    @Override public void onStartup(ServletContext servletContext) throws ServletException { 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.scan("rest"); context.register(this.getClass(), org.springdoc.webmvc.ui.SwaggerConfig.class, org.springdoc.core.SwaggerUiConfigProperties.class, org.springdoc.core.SwaggerUiOAuthProperties.class, org.springdoc.webmvc.core.SpringDocWebMvcConfiguration.class, org.springdoc.webmvc.core.MultipleOpenApiSupportConfiguration.class, org.springdoc.core.SpringDocConfiguration.class, org.springdoc.core.SpringDocConfigProperties.class, org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration.class); return context;

    Depending on your module, you can find them on the file: spring.factories 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:

    For testing purposes only, you can test temporarily using the last springdoc-openapi SNAPSHOT

    To achieve that, you can on your pom.xml or your settings.xml the following section:

    <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>
    SpringDocUtils.getConfig().replaceWithSchema(MonetaryAmount.class, new ObjectSchema()
                .addProperties("amount", new NumberSchema()).example(99.96)
                .addProperties("currency", new StringSchema().example("USD")));
    

    12.65. How can i aggregate external endpoints (exposing OPENAPI 3 spec) inside one single application?

    The properties springdoc.swagger-ui.urls.*, are suitable to configure external (/v3/api-docs url). For example, if you want to aggregate all the endpoints of other services, inside one single application. IMPORTANT: Don’t forget that CORS needs to be enabled as well.

    12.66. How can use custom json/yml file instead of generated one?

    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.

    12.67. How can i enable CSRF support?

    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:

    12.69. Is @PageableDefault supported, to enhance the OpenAPI 3 documentation?

    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

    12.70. How can I make spring security login-endpoint visible?

    You can use the following property:

    springdoc.show-login-endpoint=true

    12.72. How to override @Deprecated?

    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

    12.75. How can i define different schemas for the same class?

    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;
    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);
    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));
    
    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);
        public SwaggerIndexTransformer swaggerIndexTransformer(
                SwaggerUiConfigProperties a,
                SwaggerUiOAuthProperties b,
                SwaggerUiConfigParameters c,
                SwaggerWelcomeCommon d) {
            return new SwaggerCodeBlockTransformer(a, b, c, d);
    

    12.78. What is the compatibility matrix of springdoc-openapi with spring-boot ?

    springdoc-openapi is compatible with spring-boot 1 and spring-boot 2.

    In general, you should only pick the last stable version as per today 1.8.0.

    More precisely, this the exhaustive list of spring-boot versions against which springdoc-openapi has been built:

    12.79. Why am i getting an error: 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()));