How to change swagger-ui.html default path
Asked Answered
M

7

23

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

Munition answered 25/7, 2019 at 2:0 Comment(3)
Have a look at this: github.com/springfox/springfox/issues/1080Aeromancy
Possible duplicate of How to change Swagger-ui URL prefix?Collection
Check this, https://mcmap.net/q/589227/-how-to-change-swagger-ui-url-prefixOrthman
A
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
Aide answered 29/7, 2020 at 15:15 Comment(3)
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?Bishopric
@MarcinK. are you using springdoc or springfox?Acrobatics
@Acrobatics 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.Bishopric
G
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

Gauthier answered 17/5, 2021 at 20:59 Comment(0)
A
3

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

Alas answered 13/7, 2021 at 6:30 Comment(2)
getting error: undefined localhost:8080/custom-path/v2/api-docs when using this to set swagger custom pathFrazer
is it possible to have just /documentation? So it will be "localhost:8080/documentation" no "swagger-ui" after documentation.Acrobatics
S
2

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

Sparling answered 8/11, 2021 at 11:53 Comment(0)
H
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 protected]
    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")
Heterologous answered 26/4, 2020 at 17:53 Comment(0)
D
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/");
    }
}
Dekeles answered 8/12, 2022 at 8:57 Comment(0)
D
-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.

Diaphaneity answered 12/2, 2020 at 7:35 Comment(1)
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.Bishopric

© 2022 - 2024 — McMap. All rights reserved.