Spring Boot Redirect to SwaggerUI

Problem

Some services don’t have an UI and the OpenAPI/ Swagger UI should be used as default UI of the service. As so the root should be redirected directly to the SwaggerUI.

Solution

Just add a WebMvc redirect.

@Configuration
public class OpenApiConfig implements WebMvcConfigurer {
  @Override
  public void addViewControllers(final ViewControllerRegistry registry) {
    registry.addRedirectViewController("/", "/swagger-ui.html");
    // use setStatusCode(HttpStatus.XYZ) for any custom status code if required, e.g. MOVED_PERMANENTLY
    registry.addRedirectViewController("/swagger-ui", "/swagger-ui.html");
    // any other alias
  }
}

Swagger Open API dependencies

Spring Boot 2.x

Ensure you check the current version:

        <dependency>
            <groupId>org.springdoc</groupId>
            <artifactId>springdoc-openapi-ui</artifactId>
            <version>1.7.0</version>
        </dependency>
       <!-- if spring security is used -->
        <dependency>
            <groupId>org.springdoc</groupId>
            <artifactId>springdoc-openapi-security</artifactId>
            <version>1.7.0</version>
        </dependency>

Spring Boot 3.x

Ensure you check the current version:

        <dependency>
            <groupId>org.springdoc</groupId>
            <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
            <version>2.1.0</version>
        </dependency>

With the new version you can also use the application.yml to configure the root directory as swagger ui:

springdoc:
  swagger-ui:
    use-root-path: true

Links

Paul Sterl has written 51 articles

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>