20

I wanna change my swagger-ui path from localhost:8080/swagger-ui.html to localhost:8080/myapi/swagger-ui.html in springboot redirect is helpless to me

ink
  • 519
  • 6
  • 19
Chen Zhang
  • 201
  • 1
  • 2
  • 3

7 Answers7

15

In the application.properties of Spring Boot

springdoc.swagger-ui.path=/swagger-ui-custom.html

in your case it will be

springdoc.swagger-ui.path=/myapi/swagger-ui.html
Dima Kozhevin
  • 3,602
  • 9
  • 39
  • 52
Anil Dabas
  • 169
  • 1
  • 3
  • 1
    Hey! This doesn't work for me. Do you know if there are any other places that take precedence or if I may need to enable something? – Marcin K. Nov 29 '21 at 14:40
  • @MarcinK. are you using springdoc or springfox? – Cugomastik Feb 14 '23 at 14:06
  • @Cugomastik Hey! Thanks for being helpful, but sadly I no longer have access to this project. Sadly because I would love to provide the solution that helped me to the others. – Marcin K. Feb 14 '23 at 16:52
3

if for some reason you don't want redirect to /swagger-ui.html you can set itself contents as home view, setting an index.html at resources/static/index.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Welcome to another awesome Microservice</title>
</head>
<body>
    <script>
        document.body.innerHTML = '<object type="text/html" data="/swagger-ui.html" style="overflow:hidden;overflow-x:hidden;overflow-y:hidden;height:100%;width:100%;position:absolute;top:0px;left:0px;right:0px;bottom:0px"></object>';
    </script>
</body>
</html>

then accessing to your http://localhost:8080/ you will see your swagger docs.

finally you can customize path and .html file using:

registry.addViewController("/swagger").setViewName("forward:/index.html");

like suggests this answer

63RMAN
  • 519
  • 4
  • 6
2

You can modify springfox properties in application.properties

For example, to edit the base-url

springfox.documentation.swagger-ui.base-url=documentation

For e.g. setting it to /documentation will put swagger-ui at /documentation/swagger-ui/index.html

Rishav
  • 3,818
  • 1
  • 31
  • 49
  • 1
    getting error: undefined http://localhost:8080/custom-path/v2/api-docs when using this to set swagger custom path – Anjani Mittal Sep 12 '22 at 07:20
  • is it possible to have just /documentation? So it will be "localhost:8080/documentation" no "swagger-ui" after documentation. – Cugomastik Feb 13 '23 at 21:20
0

If you want to add, for example, documentation prefix - You can do like this for path http://localhost:8080/documentation/swagger-ui.html:

kotlin

@Configuration
@EnableSwagger2
@ConfigurationPropertiesScan("your.package.config")
@Import(value = [BeanValidatorPluginsConfiguration::class])
class SwaggerConfiguration(
    private val swaggerContactProp: SwaggerContactProp, private val swaggerProp: SwaggerProp
) : WebMvcConfigurationSupport() {

    // https://springfox.github.io/springfox/docs/current/
    @Bean
    fun api(): Docket = Docket(DocumentationType.SWAGGER_2)
        .groupName("Cards")
        .apiInfo(getApiInfo())
        .select()
        .apis(RequestHandlerSelectors.basePackage("your.controllers.folder"))
        .paths(PathSelectors.any())
        .build()

    private fun getApiInfo(): ApiInfo {
        val contact = Contact(swaggerContactProp.name, swaggerContactProp.url, swaggerContactProp.mail)
        return ApiInfoBuilder()
            .title(swaggerProp.title)
            .description(swaggerProp.description)
            .version(swaggerProp.version)
            .contact(contact)
            .build()
    }

    override fun addViewControllers(registry: ViewControllerRegistry) {
        with(registry) {
            addRedirectViewController("/documentation/v2/api-docs", "/v2/api-docs").setKeepQueryParams(true)
            addRedirectViewController(
                "/documentation/swagger-resources/configuration/ui", "/swagger-resources/configuration/ui"
            )
            addRedirectViewController(
                "/documentation/swagger-resources/configuration/security", "/swagger-resources/configuration/security"
            )
            addRedirectViewController("/documentation/swagger-resources", "/swagger-resources")
        }
    }

    override fun addResourceHandlers(registry: ResourceHandlerRegistry) {
        registry.addResourceHandler("/documentation/**").addResourceLocations("classpath:/META-INF/resources/")
    }
}

@ConfigurationProperties(prefix = "swagger")
@ConstructorBinding
data class SwaggerProp(val title: String, val description: String, val version: String)

@ConfigurationProperties(prefix = "swagger.contact")
@ConstructorBinding
data class SwaggerContactProp(val mail: String, val url: String, val name: String)

and in applicatiom.yml:


swagger:
  title: Cards
  version: 1.0
  description: Documentation for API
  contact:
    mail: email@gmail.com
    url: some-url.com
    name: COLABA card

Also don't forget to add in build.gradle.kts:

                implementation("io.springfox:springfox-swagger2:$swagger")
                implementation("io.springfox:springfox-swagger-ui:$swagger")
                implementation("io.springfox:springfox-bean-validators:$swagger")
Dmitry Kaltovich
  • 2,046
  • 19
  • 21
0

I've found several possible solutions for myself. Maybe it will be helpful for somebody else.


Set springdoc.swagger-ui.path directly

The straightforward way is to set property springdoc.swagger-ui.path=/custom/path. It will work perfectly if you can hardcode swagger path in your application.


Override springdoc.swagger-ui.path property

You can change default swagger-ui path programmatically using ApplicationListener<ApplicationPreparedEvent>. The idea is simple - override springdoc.swagger-ui.path=/custom/path before your Spring Boot application starts.

@Component
public class SwaggerConfiguration implements ApplicationListener<ApplicationPreparedEvent> {

    @Override
    public void onApplicationEvent(final ApplicationPreparedEvent event) {
        ConfigurableEnvironment environment = event.getApplicationContext().getEnvironment();
        Properties props = new Properties();
        props.put("springdoc.swagger-ui.path", swaggerPath());
        environment.getPropertySources()
                .addFirst(new PropertiesPropertySource("programmatically", props));
    }

    private String swaggerPath() {
        return "/swagger/path"; //todo: implement your logic here.
    }
}

In this case, you must register the listener before your application start:

@SpringBootApplication
@OpenAPIDefinition(info = @Info(title = "APIs", version = "0.0.1", description = "APIs v0.0.1"))
public class App {
    public static void main(String[] args) {
        SpringApplication application = new SpringApplication(App.class);
        application.addListeners(new SwaggerConfiguration());
        application.run(args);
    }
}

Redirect using controller


You can also register your own controller and make a simple redirect as suggested there.

Redirect code for Spring WebFlux applications:

@RestController
public class SwaggerEndpoint {

    @GetMapping("/custom/path")
    public Mono<Void> api(ServerHttpResponse response) {
        response.setStatusCode(HttpStatus.PERMANENT_REDIRECT);
        response.getHeaders().setLocation(URI.create("/swagger-ui.html"));
        return response.setComplete();
    }
}

The problem with such an approach - your server will still respond if you call it by address "/swagger-ui.html".

Volodya Lombrozo
  • 2,325
  • 2
  • 16
  • 34
0

You can use this code, it worked for me

package com.swagger.api.redirect;

import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

public class SwaggerApiReDirector implements WebMvcConfigurer {
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addRedirectViewController("/documentation/v2/api-docs", "/v2/api-docs");
        registry.addRedirectViewController("/documentation/configuration/ui", "/configuration/ui");
        registry.addRedirectViewController("/documentation/configuration/security", "/configuration/security");
        registry.addRedirectViewController("/documentation/swagger-resources", "/swagger-resources");
        registry.addRedirectViewController("/documentation/swagger-resources/configuration/ui", "/swagger-resources/configuration/ui");
        registry.addRedirectViewController("/documentation", "/documentation/swagger-ui.html");
        registry.addRedirectViewController("/documentation/", "/documentation/swagger-ui.html");
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry
                .addResourceHandler("/documentation/**").addResourceLocations("classpath:/META-INF/resources/");
    }
}
Ziaullhaq Savanur
  • 1,848
  • 2
  • 17
  • 20
-3

If you are using spring boot then please update application.properties file and write here

server.servlet.context-path=/myapi

it will redirect you as you want.

Yunnosch
  • 26,130
  • 9
  • 42
  • 54
  • Correct me if I'm wrong but that will prepend /myapi to all paths i.e. it will also change any REST controller from /myapi/something/something2 to /myapi/myapi/something/something2. – Marcin K. Nov 29 '21 at 14:22