Search code examples
spring-boothttp-redirectopenapispringdoc

OpenApi 3 with Spring Boot 3 - how to declare a redirect from "/" to "/swagger-ui/index.html"?


We are migrating the API documentation from a swagger.yaml file to annotations in the controllers.

The main reason for this work is that any changes to the API require work in more than one place. The .yaml file needs to be validated, the interface re-generated and implemented. There is a chance that changes to the code may not be reflected in the .yaml file.

While it is working fine using io.swagger.v3.(...), if I explicitly enter the full URL https://localhost:8443/swagger-ui/index.html it will resolve the OpenAPI page.

But, if I enter https://localhost:8443 the following method is hit as it prints out https://localhost:8443/swagger-ui/index.html but does not redirect to that page.

@RestController
public class Controller {    

    @GetMapping(value = "")
    public String index() {
        var baseUrl = ServletUriComponentsBuilder.fromCurrentContextPath().build().toUriString();

        String redirect = String.format("redirect:%s/swagger-ui/index.html", baseUrl);
        System.out.println(redirect);
        return redirect;
    }
    // other methods
}

Using the method above shows the "/" endpoint in the OpenAPI page, which I don't want.


Solution

  • To access swagger-ui directly from the application root path, instead of the endpoint for redirection, add the following property to application.properties:

    springdoc.swagger-ui.use-root-path=true