I am using swagger 2 with spring mvc.
The war file is web-app.war and Swagger base URL is shown as /web-app/rest/api
I would like to remove the war context path so the api call can be made as
example.com/rest/api
and not example.com/web-app/rest/api
SwaggerConfig.java
@Configuration
@EnableWebMvc
@EnableSwagger2
public class SwaggerConfig extends WebMvcConfigurerAdapter {
@Bean
public Docket api() {
// @formatter:off
return new Docket(DocumentationType.SWAGGER_2)
.useDefaultResponseMessages(false)
.pathMapping("/")
.select()
.apis(RequestHandlerSelectors.any())
.build().apiInfo(apiInfo());
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder().title("Rest API")
.description("Describes the restful interface")
.build();
}
@Override
public void addResourceHandlers(final ResourceHandlerRegistry registry) {
registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
}
}
If /web-app
is your context root (you can change it in your IDE, plenty of tutorials online on how to do that) -- then there is no way you can place an element of your project outside that.
To achieve what you want, you could set the context root to /
and then prefix your REST services with web-app
. This keeps the same REST path, but places the Swagger API at /rest/api
.
EDIT
If you believe Springfox has wrongly determined your base path, you can add a PathProvider
to the Docket
definition:
return new Docket(DocumentationType.SWAGGER_2)
/*other options*/
.pathProvider(new PathProvider(){
String getApplicationBasePath(){
return "/";
}
/*implement other methods or extend RelativePathProvider or Absolute PathProvider instead */
}
To solve this issue, need to change the host property of the Docket. Otherwise, the basePath will be determined based on the request url (as per Swagger2Controller and how to change base path for swagger)
@Bean
public Docket api(ServletContext servletContext) throws LoadPropertiesException {
String host = "example.com";
String applicationBasePath = null;
return new Docket(DocumentationType.SWAGGER_2)
.groupName("My API").host(host).pathProvider(new RelativePathProvider(servletContext) {
@Override
public String getApplicationBasePath() {
return applicationBasePath;
}
})
.select()
.apis(Predicates.not(RequestHandlerSelectors.basePackage("org.springframework.boot"))) .apis(Predicates.not(RequestHandlerSelectors.basePackage("org.springframework.cloud"))) .apis(Predicates.not(RequestHandlerSelectors.basePackage("org.springframework.data.rest.webmvc")))
.build()
.apiInfo(apiInfo());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With