Added Springfox Swagger-UI and it's not working, what am I missing?

114.4k views Asked by At

Following the instructions here:

http://www.baeldung.com/swagger-2-documentation-for-spring-rest-api

I added these dependencies to my project:

compile "io.springfox:springfox-swagger2:2.7.0"
compile "io.springfox:springfox-swagger-ui:2.7.0"

and configured SpringFox Swagger like this:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any())
                .build();
    }
}

but the Swagger UI seems not to get enabled. I tried:

and all I get is:

Whitelabel Error Page

This application has no explicit mapping for /error, so you are seeing this as a fallback.

Mon Sep 11 09:43:46 BST 2017
There was an unexpected error (type=Method Not Allowed, status=405).
Request method 'GET' not supported

and on the logs I see:

2017-09-11 09:54:31.020  WARN 15688 --- [nio-8080-exec-6] o.s.web.servlet.PageNotFound             : Request method 'GET' not supported
2017-09-11 09:54:31.020  WARN 15688 --- [nio-8080-exec-6] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved exception caused by Handler execution: org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'GET' not supported

http://localhost:8080/swagger-resources returns:

[{"name": "default",
  "location": "/v2/api-docs",
  "swaggerVersion": "2.0"}]

What am I missing?

24

There are 24 answers

0
StanislavL On BEST ANSWER

I ran into this issue because I had endpoints with request mappings that had path variables of this form: /{var}. Turns out that this is an issue for both GET and POST endpoints i.e. GET /{var} and POST /{var} block swagger-ui. Once I made the paths more specific, I got swagger-ui to work.

Quote from https://github.com/springfox/springfox/issues/1672

When spring finds a simple path with just one variable swagger cannot intercept the URLs.

Found by investigating various ideas in comments.

1
Ravi Parekh On

Springfox 3.0.0 only works with Spring Boot <= 2.6.0-M2 but not with versions above it

Options for Spring Boot 2.6 M2 <
1. spring.mvc.pathmatch.matching-strategy=ANT_PATH_MATCHER #-> App.properties
    -    But without Actuator
2. @EnableWebMvc
3. Migrate to springdoc-openapi-ui - same steps as io.springfox >= 3.X

io.springfox >= 2.X

io.springfox >= 3.X

<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-schema</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
browser URL
http://localhost:8080/swagger-ui.html
browser URL
http://localhost:8080/swagger-ui/
http://localhost:8080/swagger-ui/index.html
Must Need

mvn clean

Must Need

mvn clean

@Configuration
@EnableSwagger2
@Configuration
@EnableSwagger2
4
viveknaskar On

Already a lot of answers have stated the right answer but still, there has been some confusion regarding the error.

If you are using Spring Boot Version >= 2.2, it is recommended to use SpringFox Swagger version 3.0.0

Now, only a single dependency is required to be added in the pom.xml.

<!-- Swagger dependency -->
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-boot-starter</artifactId>
        <version>3.0.0</version>
    </dependency>

Once the application is started, you can get the documentation by hitting either of the new swagger URLs.

Option 1: http://localhost:8080/swagger-ui/

Option 2: http://localhost:8080/swagger-ui/index.html

1
Suresh On

Had to do 2 things to fix it:

  1. added the below dependency and removed other swagger dependencies

    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-boot-starter</artifactId>
        <version>3.0.0</version>
    </dependency>
    
  2. org.springframework.security dependency in pom.xml was blocking the swagger-ui, so added below code to bypass security for swagger UI:

     @Configuration
     public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
         @Override
         public void configure(WebSecurity web) throws Exception {
             web.ignoring().antMatchers("/v2/api-docs",
                                        "/swagger-resources/**",
                                        "/swagger-ui/**");
         }
     }
    
0
jonathanlima On

For version 3.0.0 only one dependency:

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-boot-starter</artifactId>
    <version>3.0.0</version>
</dependency>

After that you can access the swagger-ui on:

  • http://localhost:8080/swagger-ui/#
  • http://localhost:8080/swagger-ui/index.html

for version 2.x.x

<dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger2</artifactId>
        <version>${io.springfox.version}</version>
</dependency>
<dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger-ui</artifactId>
        <version>${io.springfox.version}</version>
</dependency>

Access the swagger-ui on: http://localhost:8080/swagger-ui

1
NIKHIL CHAURASIA On

If you are using Spring Boot Version >= 2.2, I recommend using SpringFox Swagger version 3.0.0. Keep your pom.xml dependency configuration like this:

<dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-boot-starter</artifactId>
        <version>3.0.0</version>
</dependency>

Keep your Swagger configuration class like below:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

@Configuration
@EnableSwagger2
public class SwaggerConfig {

public static final Contact DEFAULT_CONTACT = new Contact(
        "Sample App", "http://www.sample.com", "[email protected]");

public static final ApiInfo DEFAULT_API_INFO = new ApiInfo(
        "Awesome API Title", "Awesome API Description", "1.0",
        "urn:tos", DEFAULT_CONTACT,
        "Apache 2.0", "http://www.apache.org/licenses/LICENSE-2.0", Arrays.asList());

private static final Set<String> DEFAULT_PRODUCES_AND_CONSUMES =
        new HashSet<String>(Arrays.asList("application/json",
                "application/xml"));

@Bean
public Docket api() {
    return new Docket(DocumentationType.SWAGGER_2)
            .apiInfo(DEFAULT_API_INFO)
            .produces(DEFAULT_PRODUCES_AND_CONSUMES)
            .consumes(DEFAULT_PRODUCES_AND_CONSUMES);
 }
}

Now, access your swagger UI by going to this URL: http://localhost:8080/swagger-ui/index.html#/

0
Aditya Rewari On

For me, it turned out to be an issue because of existing APIs

I had an Existing API at controller which was like

http://localhost:8080/{PathParam}

I changed it to

http://localhost:8080/domain/{PathParam}

and the issue was resolved !!!

0
dean deng On

Add @RequestMapping("/") at the controller level, It works.

0
M ONeill On

Try restarting your IDE.

After trying many of these suggestions and still not having any luck, I came across this blog post: https://medium.com/swlh/openapi-swagger-ui-codegen-with-spring-boot-1afb1c0a570e

Where the author stated, "Note: If you are getting Whitelabel Error Page try to restart your IDE and run the project again."

This worked like a charm.

1
RoundedHouse On

io.springfox >= 3, and using SpringSecurity also

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
    <dependency>
        <groupId>io.jsonwebtoken</groupId>
        <artifactId>jjwt</artifactId>
        <version>0.9.1</version>
    </dependency>
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-boot-starter</artifactId>
        <version>3.0.0</version>
    </dependency>

SpringFoxConfig Class

@Configuration
@EnableSwagger2
public class SpringFoxConfig implements WebMvcConfigurer {
@Bean
public Docket api() {
    return new Docket(DocumentationType.SWAGGER_2)
            .select()
            .apis(RequestHandlerSelectors.any())
            .paths(PathSelectors.any())
            .build()
            .apiInfo(getApiInfo());
}

private ApiInfo getApiInfo() {
    return new ApiInfo(
            "company_name",
            "message here",
            "VERSION_1",
            "TERMS OF SERVICE URL",
            new Contact("company", "url", "EMAIL"),
            "LICENSE",
            "LICENSE URL",
            Collections.emptyList()
      );
     }
   }

WebConfig Class (Make sure @EnableWebMvc annotation is not used else you will run into error)

   @Configuration
  //@EnableWebMvc
   public class WebConfig implements WebMvcConfigurer {
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**")
                .allowedMethods("HEAD", "GET", "POST", "PUT", "DELETE", "PATCH", 
           "OPTIONS");
        }
      }

SecurityConfiguration class

@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
private static final String[] AUTH_WHITELIST = {
        // -- Swagger UI v2
        "/v2/api-docs",
        "/swagger-resources",
        "/swagger-resources/**",
        "/configuration/ui",
        "/configuration/**",
        "/configuration/security",
        "/swagger-ui.html",
        "/webjars/**",
        // -- Swagger UI v3 (OpenAPI)
        "/v3/api-docs/**",
        "/swagger-ui/**",
        "/swagger-ui/",
        "/swagger-ui"
        // other public endpoints of your API may be appended to this array

        @Override
protected void configure(HttpSecurity httpSecurity) throws Exception{
    httpSecurity.cors();
    httpSecurity.csrf().disable();
    httpSecurity.sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                .antMatchers(AUTH_WHITELIST).permitAll()
                .anyRequest()
                .authenticated();

                httpSecurity.addFilterBefore(jwtRequestFilter, 
                             UsernamePasswordAuthenticationFilter.class);
         }
     };
0
Madhuka Dilhan On

if You use Version - V3 || io.springfox >= 3.0.0

<dependency>
   <groupId>io.springfox</groupId>
   <artifactId>springfox-boot-starter</artifactId>
   <version>3.0.0</version>
</dependency>

Java code

@Configuration
@EnableSwagger2

public class SwaggerConfig {

@Bean
public Docket api() {
    return new Docket(DocumentationType.SWAGGER_2).select()
            .apis(RequestHandlerSelectors.basePackage("Your Controller package name"))
            .paths(PathSelectors.any()).build();
}

}

V3 browser URL -> http://localhost:8080/swagger-ui/#/ Run (Must need) : Mvn clean

1
Jakub Słowikowski On

I was trying to combine Swagger @Configuration class with @EnableWebMvc class in a single file.

NOT WORKING:

@Configuration
@EnableSwagger2
@EnableWebMvc
public class SwaggerConfiguration extends WebMvcConfigurerAdapter {

    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any())
                .build();
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/swagger-ui/**")
                .addResourceLocations("classpath:/META-INF/resources/");

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

SOLUTION was to make it in 2 separate java classes like in docs:

@Configuration
@EnableSwagger2
public class SwaggerConfiguration {

    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any())
                .build();
    }
}


@Configuration
@EnableWebMvc
public class WebAppConfig implements WebMvcConfigurer {

    @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/");
    }

}
0
Prasanth Rajendran On

Adding @RequestMapping("/") in controller level(after @RestController\@Controller annotation) helps me to get rid of the Request method 'GET' not supported issue. Thanks to Dhermanns's suggestion

0
jakub-adamczewski On

This comment saved a lot of my time. In short - I found that someone in my project added mapping to controller like this:

@RestController("/api/test")

but of course it should look like this:

@RestController
@RequestMapping("/api/test")

Because of above I got 405 responses while trying to see swagger-ui.

@RestConroller's docs explain the issue more precisely:

The value may indicate a suggestion for a logical component name, to be turned into a Spring bean in case of an autodetected component. Returns: the suggested component name, if any (or empty String otherwise) Since: 4.0.1

0
in3des On

I had similar problem recently

http://localhost:8080/swagger-ui/ - didn't work

http://localhost:8080/swagger-ui/index.html - worked fine

...at the end the issue was caused by some mess in my pom.xml

<dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger2</artifactId>
        <version>3.0.0</version>
    </dependency>

    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger-ui</artifactId>
        <version>3.0.0</version>
    </dependency>

    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-boot-starter</artifactId>
        <version>3.0.0</version>
    </dependency>

I deleted the first two dependencies, so only springfox-boot-starter left and after couple of maven cleanups and restarting the app the first path started to work fine as well http://localhost:8080/swagger-ui/

0
Alex Osmolovsky On

If you want to use Version 3.0 you also have to change DocumentationType to OAS_30 in the Docket Constructor:

@Bean
public Docket api() {
  return new Docket(DocumentationType.OAS_30)
                           .select()
                           .apis(RequestHandlerSelectors.any())
                           .paths(PathSelectors.any())
                           .build();
}
0
Ömer Talha Yurttutan On

i just removed @EnableSwagger2 and it worked

0
Imran On

I simply reloaded my maven and it had worked for me I have the following dependencies in my POM file. ` 4.0.0 org.springframework.boot spring-boot-starter-parent 2.7.4 com.example demo 0.0.1-SNAPSHOT demo Demo project for Spring Boot <java.version>1.8</java.version>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-rest</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jdbc</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <scope>runtime</scope>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.29</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger-ui</artifactId>
        <version>3.0.0</version>
    </dependency>


    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-boot-starter</artifactId>
        <version>3.0.0</version>
    </dependency>


</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>
`
0
boardtc On

What worked for me is likely very bespoke. For some reason running the app via IntelliJ, though I included spring-boot-starter-web in the pom.xml, Tomcat was not starting.

The solution was running the application via Maven:

mvn spring-boot:run 

started Tomcat and all of a sudden http://localhost:8080/swagger-ui/index.html was active and working.

0
iengchen On

Conclusion: I find there are no jar files under maven repository ${user_home}/.m2/repository/io/springfox/springfox-swagger-ui/2.9.2,after below steps everything is ok.

I solved this issue by follow steps:

  • go to ${user_home}/.m2/repository/io/springfox/springfox-swagger-ui/2.9.2
  • examine whether the files under 2.9.2 is complete。if there are missing files,delete the whole 2.9.2 directory
  • execute reimport all maven projects in intellij idea

My spring boot version is 2.2.2.

0
Aswani On

I got swagger issue /swagger-ui.html request method 'get' not supported\request method 'get' not supported.\supported methods post

I was able to fix the issue

In my controller api @RequestMapping() doesn't have path info. provided path like below Fix - @RequestMapping(value = '/v1/createAnalytic')

5
Muralidharan.rade On

I tried most of these answers and the final solution was creeping..

The right URL is the following

http://localhost:8080/swagger-ui/

I'm using Springfox swagger-ui 3.x.x

Refer for complete swagger setup: http://muralitechblog.com/swagger-rest-api-dcoumentation-for-spring-boot/

0
Ousama On

For Spring Version >= 2.2, you should add the dependency springfox-boot-starter

pom.xml:

<properties>
    <java.version>1.8</java.version>
    <io.springfox.version>3.0.0</io.springfox.version>
</properties>

<dependencies>
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger2</artifactId>
        <version>${io.springfox.version}</version>
    </dependency>
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger-ui</artifactId>
        <version>${io.springfox.version}</version>
    </dependency>
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-data-rest</artifactId>
        <version>${io.springfox.version}</version>
    </dependency>
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-bean-validators</artifactId>
        <version>${io.springfox.version}</version>
    </dependency>
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-boot-starter</artifactId>
        <version>${io.springfox.version}</version>
    </dependency>
</dependencies>

ApplicationSwaggerConfig

@Configuration
@EnableSwagger2
public class ApplicationSwaggerConfig {

    @Bean
    public Docket employeeApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any())
                .build();
    }

}

Swagger-UI link: http://localhost:8080/swagger-ui/index.html#/

0
fpezzini On

I also ran into this and the issue was that we had a controller without path mapping (thus mapping to "/"). That was blocking the requests to the swagger-ui resources.