21
votes

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?

14
Do you have any spring security which could prevent the access?StanislavL
@StanislavL: no, I haven't enabled security yet.pupeno
@StanislavL: I added the log errors I'm getting and it's a PageNotFound.pupeno
@Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2).groupName("users-public-api") .select() .apis(RequestHandlerSelectors.any()) .paths(PathSelectors.any()) .build() .pathMapping("/") .enableUrlTemplating(false); } that's my working config.StanislavL
@StanislavL: I tried with that, same error.pupeno

14 Answers

9
votes

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.

22
votes

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/

16
votes

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

15
votes
  1. io.springfox >= 2.X
  2. io.springfox >= 3.X

After going through many solution nothing worked. but

Version - V2 || io.springfox <= 2.X.0

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

V2 browser URL -> http://localhost:8080/swagger-ui.html


Version - V3 || io.springfox >= 3.0.0

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

V3 browser URL -> http://localhost:8080/swagger-ui/#/

Run (Must need) : Mvn clean

@Configuration
@EnableSwagger2

No need to add new Docket Bean for simple swagger configuration(i.e. path and basepackage)

V2 and V3

5
votes

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#/

3
votes

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

2
votes

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#/

1
votes

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.

0
votes

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
votes

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

0
votes

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
votes

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')

0
votes

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
votes

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