springfox: swagger-ui endpoint doesn't seem to work

I’m trying to figure out how to get at the Swagger UI using the Springfox artifacts in a Spring Boot MVC application. Unfortunately the reference documentation is rather misleading, since the neither documented endpoint or the (different) endpoint in the screenshot exist in my application.

I’m using the following dependencies in Maven:

<dependency>
  <groupId>io.swagger</groupId>
  <artifactId>swagger-jaxrs</artifactId>
  <version>1.5.0</version>
</dependency>
<dependency>
  <groupId>io.springfox</groupId>
  <artifactId>springfox-swagger2</artifactId>
  <version>2.0.1</version>
  </dependency>
<dependency>
  <groupId>io.springfox</groupId>
  <artifactId>springfox-swagger-ui</artifactId>
  <version>2.0.1</version>
</dependency>

My Docket Bean is very simple for now:

    @Bean
    public Docket myAPI() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .paths(paths())
                .build();
    }

Looking at /mappings in Spring Boot, I have /swagger-resources and /v2/api-docs, but can’t find an endpoint for the UI.

Am I doing something wrong, experiencing a bug, or suffering from bad documentation?

About this issue

  • Original URL
  • State: closed
  • Created 9 years ago
  • Reactions: 15
  • Comments: 57 (18 by maintainers)

Most upvoted comments

I have added following in the class where i put @EnableWebMvc annotation. It works fine for me.

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {

       registry.addResourceHandler("swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");

        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");

}

I have removed the extra swagger 1.5.0 dependency and ensured that I am using the wordnik package names for the API annotations. This appears to make no difference to the resulting behaviour.

My application is defined with the following annotations:

@Configuration
@EnableAutoConfiguration
@ComponentScan
@EnableSwagger2
public class Application {
    // ...
}

I did have an @Configuration class with @EnableWebMvc on it. Removing the @EnableWebMvc annotation seems to fix the missing /swagger-ui.html endpoint. The documentation implies the opposite is true, stating that adding the annotation may fix a NullPointerException.

I had to disable security configurations for various swagger-ui related endpoints to get the UI to load properly, but I got there in the end. Thanks for your help.

Ok figured it out. The dispatcherServlet is suppose to map /** to to ResourceHttpRequestHandler, but if you have a request mapping that takes one parameter in my case (@RequestMapping("/{range}")) then it will override it.

I thought this would be ok, because the @RestController class had @RequestMapping(“/query”) annotation (thus the full path being /query/{range}) but apparently not.

So there you go.

You also have to be aware that Swagger 3 changed the URL of the UI from /swagger-ui.html to /swagger-ui/index.html.

I was surprised by seeing the Whitelabel Error Page (404: NotFound) after upgrading from 2.8.0 to Swagger 3.

Thanks to @hala3k for the mentioned link that helped me clarify this.

for me after removing @EnableWebMvc it worked.

@NetRob I just added, for 3.0.0:

@Configuration
class SwaggerUiWebFluxConfigurer : WebFluxConfigurer {
    override fun addResourceHandlers(registry: ResourceHandlerRegistry) {
        registry.addResourceHandler("/swagger-ui/**")
            .addResourceLocations("classpath:/META-INF/resources/webjars/springfox-swagger-ui/")
            .resourceChain(false)
    }
}

Do you by any chance have a custom webconfigurer adapter or perhaps a @EnableWebMvc?

Also 2.0.1 will not work with swagger 1.5.0 ( depends on milestone). The package names have changed between the milestone and release builds.

@igilham mappings will only list RequestMapping’s. <HOST:PORT/CONTEXT_PATH>/swagger-ui.html should reveal the ui. Not sure whats misleading about this?

I had a similar issue and found the reason of what was wrong with my code. I had a class marked by @Configuration derived from WebMvcConfigurationSupport.

Unfortunately, WebMvcConfigurationSupport has an empry method configureDefaultServletHandling() which has to be overriden like this:

@Override protected void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { configurer.enable(); }

The solution, that has helped me, was to include the aforementioned resource handlers in the class, that enables @EnableWebMvc via a WebMvcConfigurerAdapter:

My class where I needed to activate @EnableWebMvc was the SecurityConfiguration in order to set up Cors mappings. So I moved the swagger resource configuration there: (The solution is ugly, because swagger does not belong into security. But then, spring itself is ugly.)

@Configuration
@EnableWebMvc
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
                    // ... a lot of security stuff
        @Bean
        public WebMvcConfigurer webMvcConfigurer() {
                    return new WebMvcConfigurerAdapter() {
        @Override
        public void addCorsMappings(CorsRegistry registry) {  // this is the reason I needed             @EnableWebMvc 
            registry.addMapping("/api/**").allowedOrigins("*");
        }

        @Override
        public void addResourceHandlers(ResourceHandlerRegistry registry) { // this does not belong here, but now it gets picked up by spring
            registry.addResourceHandler("swagger-ui.html")
                    .addResourceLocations("classpath:/META-INF/resources/");
            registry.addResourceHandler("/webjars/**")
                    .addResourceLocations("classpath:/META-INF/resources/webjars/");
        }
    };
}

Context path is dependent on your application. As a library, there is no way to know what your applications context path is. May be we should clarify that in the docs. Usually when you’re testing locally that context path is /

The screenshot is a little misleading as you said because its based on the demo the home forwards to /swagger-ui.html.

Thanks for your feedback! 👍

solved for me by using swagger 3 instead of 2 as swagger 2 might not integrate well with spring-boot 2. this link might be useful.

implementation group: 'io.springfox', name: 'springfox-swagger2', version: '3.0.0-SNAPSHOT'
implementation group: 'io.springfox', name: 'springfox-swagger-ui', version: '3.0.0-SNAPSHOT'
implementation group: 'io.springfox', name: 'springfox-spring-webflux', version: '3.0.0-SNAPSHOT'

It was working till yesterday, but now it is not working

I have one @GetMapping(value = “/fallBack”) in that service

the context path is blank port = 9208

localhost:9208/swagger-resources loading localhost:9208/swagger-ui.html not loading

@Configuration
//@EnableWebMvc
public class ResourceHandlerConfig implements WebFluxConfigurer {


	@Override
	public void addResourceHandlers(ResourceHandlerRegistry registry) {
		registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
		registry.addResourceHandler("/swagger-ui.html**").addResourceLocations("classpath:/META-INF/resources/");
		registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
		//Resource Path for Hystrix Dashboard
		registry.addResourceHandler("/hystrix/**").addResourceLocations("classpath:/static/hystrix/");
	}}



	web.server.adapter.HttpWebHandlerAdapter.traceDebug - [74c4396b] HTTP GET "/swagger-resources/", headers={masked}
	web.reactive.result.method.annotation.RequestMappingHandlerMapping.lambda$getHandler$1 - [74c4396b] Mapped to public org.springframework.http.ResponseEntity<java.util.List<springfox.documentation.swagger.web.SwaggerResource>> springfox.documentation.swagger.web.ApiResourceController.swaggerResources()
	web.reactive.result.method.annotation.ResponseEntityResultHandler.selectMediaType - Using 'application/json;q=0.8' given [text/html, application/xhtml+xml, image/webp, image/apng, application/xml;q=0.9, application/signed-exchange;v=b3;q=0.9, */*;q=0.8] and supported [application/json]
	web.reactive.result.method.annotation.ResponseEntityResultHandler.writeBody - [74c4396b] 0..1 [java.util.List<springfox.documentation.swagger.web.SwaggerResource>]
	http.codec.json.Jackson2JsonEncoder.trace - [74c4396b] Encoding [[springfox.documentation.swagger.web.SwaggerResource@4903f26e, springfox.documentation.swagger.web.SwaggerResource@57b46085, springfox.documentation.swagger.web.SwaggerResource@4beb0f82, springfox.documentation.swagger.web.SwaggerResource@3a6db652, springfox.documentation.swagger.web.SwaggerResource@6caba3f3, springfox.documentation.swagger.web.SwaggerResource@18ef56ab, springfox.documentation.swagger.web.SwaggerResource@b6bcd2b, springfox.documentation.swagger.web.SwaggerResource@5ce32532, springfox.documentation.swagger.web.SwaggerResource@6d66b166, springfox.documentation.swagger.web.SwaggerResource@fdef86f, springfox.documentation.swagger.web.SwaggerResource@5a096e2a, springfox.documentation.swagger.web.SwaggerResource@1f060aec, springfox.documentation.swagger.web.SwaggerResource@473365eb, springfox.documentation.swagger.web.SwaggerResource@3fd6e0e2]]
	web.server.adapter.HttpWebHandlerAdapter.traceDebug - [74c4396b] Completed 200 OK, headers={masked}
	http.server.reactive.ReactorHttpHandlerAdapter.trace - [74c4396b] Handling completed

	web.server.adapter.HttpWebHandlerAdapter.traceDebug - [74c4396b] HTTP GET "/swagger-ui.html", headers={masked}
	web.reactive.handler.SimpleUrlHandlerMapping.lookupHandler - [74c4396b] Matching patterns [/swagger-ui.html**, /**]
	web.reactive.handler.SimpleUrlHandlerMapping.lambda$getHandler$1 - [74c4396b] Mapped to ResourceWebHandler ["classpath:/META-INF/resources/"]
	web.reactive.resource.ResourceWebHandler.lambda$handle$0 - [74c4396b] Resource not found
	web.reactive.function.server.RouterFunctions.route - [74c4396b] Matched org.springframework.boot.autoconfigure.web.reactive.error.DefaultErrorWebExceptionHandler$$Lambda$1372/0x00000008008bb040@10209892
	web.HttpLogging.debug - [74c4396b] Resolved [ResponseStatusException: 404 NOT_FOUND] for HTTP GET /swagger-ui.html
	core.codec.CharSequenceEncoder.trace - [74c4396b] Writing "<html><body><h1>Whitelabel Error Page</h1><p>This application has no configured error view, so you are seeing this as a fallback.</p><div id='created'>Thu Jul 02 22:15:45 IST 2020</div><div>There was an unexpected error (type=Not Found, status=404).</div></body></html>"
	web.server.adapter.HttpWebHandlerAdapter.traceDebug - [74c4396b] Completed 404 NOT_FOUND, headers={masked}
	http.server.reactive.ReactorHttpHandlerAdapter.trace - [74c4396b] Handling completed


Now, I changed V to 2.10.5, & it is working fine.

Working example with complete code and dependencies using spring boot 2.0.3-RELEASE https://gist.github.com/biniama/ba3e0e1df6fd7d320d1bf242de9d469e

It is a compilation of all the recommended options from the above comments.

I had a similar issue to the one @ndtreviv was experiencing on 9 Mar 2016, however the request mapping for my controller was for “/”. I was porting a legacy application so couldn’t change the URLs of the main application and none of the suggestions above worked for me.

I worked around this issue by adding support for a different path for accessing swagger (http://localhost:8000/swagger/ui/swagger-ui.html). This required the following resource handlers to be set up:

public class SpringMvcConfiguration extends WebMvcConfigurerAdapter {
    private static final String SWAGGER_UI_PATH = "/swagger/ui";
    private static final String CONFIG_LOCATION = "classpath:/url-rewrite.xml";

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry
                .addResourceHandler(SWAGGER_UI_PATH + "/swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/")
                .resourceChain(true)
                .addResolver(new PathResourceResolver() {
                    @Override
                    protected Resource getResource(String resourcePath, Resource location) throws IOException {
                        return location.createRelative(resourcePath.substring(SWAGGER_UI_PATH.length()));
                    }
                });

        registry
                .addResourceHandler(SWAGGER_UI_PATH + "/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
    }
}

I then needed to introduce Tuckey for URL rewriting with the following configuration:

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE urlrewrite
        PUBLIC "-//tuckey.org//DTD UrlRewrite 4.0//EN"
        "http://www.tuckey.org/res/dtds/urlrewrite4.0.dtd">
<urlrewrite>
    <rule>
        <from>^/swagger/ui/swagger-resources(.*)$</from>
        <to type="permanent-redirect">/api/stock/swagger-resources/$1</to>
    </rule>

    <rule>
        <from>^/swagger/ui/v2/api-docs</from>
        <to type="permanent-redirect">/api/stock/v2/api-docs</to>
    </rule>
</urlrewrite>

Spring Boot: 1.5.4.RELEASE Swagger: 2.8.0

@raviksoni25 well, that’s interesting: I cloned your project into Spring Tools Suite and it does not work. Afterwards, I did exactly the same on another machine, and there it worked.

Unfortunately, I do not really have any clue what’s going on there. There are just some really minor differences in the logs. I’m attaching them, though. failing.txt working.txt

/edit: okay. that was a nasty one: after cleaning my ~/.m2 it does work on the first machine, too.

@shafsongithub I have pushed sample Spring boot with Swagger application. If you want you can use that. https://github.com/raviksoni25/swagger-sample.git

I found the really reason, because of @ComponentScan, and u must to annotate it , for example: //@ComponentScan(basePackages = {“com.haizhi.dao”,“com.haizhi.controll”,“com.haizhi.service”})

and then , it will be ok, u can open the swagger-tui.html and /swagger-resources/configuration/ui

For anyone still encountering this problem, I tried almost everything from above but still can’t fix it. So, this is how I resolved mine.

Root cause for my case: swagger-ui doesn’t show up because it doesn’t recognize any of my APIs.

I don’t know the way how it recognizes APIs but I’m 100% sure that it doesn’t recognize the controllers and methods I annotated with Spring shorthand annotations, annotations such as @RestController, @PostMapping, @GetMapping, etc.

When I changed it to the traditional @RequestMapping(value = "/foo", method = RequestMethod.POST), the API is now recognized and swagger-ui now shows.

Versions used:

  • springfox-swagger2:2.7.0
  • springfox-swagger-ui:2.7.0
  • spring-boot:2.0.0.RELEASE

Hope this helps anyone.

@ndtreviv You saved my day! My configuration is all right, but I just can’t see swagger-ui.html and it always returns “Method not allowed”. After reading your post, I checked all my controllers and find one with

@RequestMapping(method = RequestMethod.OPTIONS)

to handle all OPTIONS request. I deleted this controller and it just works!

In my case the issues was with version number. Changed from compile ‘io.springfox:springfox-swagger-ui:2.4.0’ to compile ‘io.springfox:springfox-swagger-ui:2.6.1’ in build.gradle file.

Unbelievable, clearing …m2 folder and rebuilding helped.