54

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?

Pablo Fernandez
  • 279,434
  • 135
  • 377
  • 622
  • Do you have any spring security which could prevent the access? – StanislavL Sep 11 '17 at 08:53
  • @StanislavL: no, I haven't enabled security yet. – Pablo Fernandez Sep 11 '17 at 08:54
  • @StanislavL: I added the log errors I'm getting and it's a PageNotFound. – Pablo Fernandez Sep 11 '17 at 08:55
  • `@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 Sep 11 '17 at 08:57
  • @StanislavL: I tried with that, same error. – Pablo Fernandez Sep 11 '17 at 08:58
  • https://github.com/springfox/springfox/issues/1672 one more possible reason from the discussion - 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. – StanislavL Sep 11 '17 at 09:02
  • @StanislavL: bingo! I commented out my single controller with an action and it started to work. – Pablo Fernandez Sep 11 '17 at 09:13
  • @StanislavL: do you want to write that comment as an answer so I can accept it? – Pablo Fernandez Sep 11 '17 at 09:21
  • Now swagger comes with two version V2 and V3, depends on requirement https://stackoverflow.com/a/64333853/410439 – Ravi Parekh Feb 18 '21 at 15:18

23 Answers23

90

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
Ravi Parekh
  • 5,253
  • 9
  • 46
  • 58
  • `@EnableSwagger2` is not required for version 3+. They recommend to delete that annotation . "Remove any @EnableSwagger2... annotations" - https://github.com/springfox/springfox – Matoosh Feb 16 '23 at 15:14
34

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/

Muralidharan.rade
  • 2,226
  • 1
  • 24
  • 34
29

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

viveknaskar
  • 2,136
  • 1
  • 20
  • 35
  • 2
    Thank you very much. This saved my day. I was entering URL as "http://localhost:8080/swagger-ui" and couldn't get the UI but with "/" at the end, it rendered like magic. Could you plz explain this "/" at the end? Is it mandatory? – Arvind Kumar Jan 29 '21 at 09:01
  • Glad that you found this useful. Yes, with the new release, the "/" at the end is mandatory. You can refer to this blog as well: https://www.baeldung.com/swagger-2-documentation-for-spring-rest-api – viveknaskar Jan 30 '21 at 15:23
  • 1
    This didn't work for me at the first place. but it worked after few try. I have no clue why. I'm facing the same issue after following the tutorial on https://www.youtube.com/watch?v=gduKpLW_vdY&t=918s&ab_channel=JavaBrains. one of the comments used this method to resolve the same issue. – stoneshishang Aug 04 '21 at 17:53
  • 1
    Thats fixed it for me, I also reomoved the old swagger dependencies. Thanks ! implementation("io.springfox:springfox-swagger2:${swaggerVersion}") implementation("io.springfox:springfox-swagger-ui:${swaggerVersion}") – SteveG Apr 08 '22 at 11:49
12

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.

StanislavL
  • 56,971
  • 9
  • 68
  • 98
9

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

Ousama
  • 2,176
  • 3
  • 21
  • 26
4

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

jonathanlima
  • 159
  • 2
  • 9
2

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.

fpezzini
  • 774
  • 1
  • 8
  • 17
2

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", "sample@gmail.com");

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

halfer
  • 19,824
  • 17
  • 99
  • 186
2

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

}
Jakub Słowikowski
  • 1,063
  • 1
  • 8
  • 13
2

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/

in3des
  • 31
  • 5
1

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

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

Prasanth Rajendran
  • 4,570
  • 2
  • 42
  • 59
0

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

Farzad Vertigo
  • 2,458
  • 1
  • 29
  • 32
0

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.

iengchen
  • 341
  • 4
  • 9
0

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

Aswani
  • 79
  • 2
  • 5
0

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

Madhuka Dilhan
  • 1,396
  • 1
  • 14
  • 21
0

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.

M ONeill
  • 39
  • 3
0

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

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

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

Aditya Rewari
  • 2,343
  • 2
  • 23
  • 36
0

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/**");
         }
     }
    
JAMSHAID
  • 1,258
  • 9
  • 32
Suresh
  • 1
  • 1
    As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Apr 14 '22 at 01:28
0

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>
`
Imran
  • 9
  • 4
0

Solution for Spring Boot version 3.0.4

As specified on the official "Open API3 & Spring Boot" documentation https://springdoc.org/

For spring-boot v3 support, be sure you use https://springdoc.org/v2/

So I just did the "Getting Started" as follow :

Inside pom.xml :

<dependency>
  <groupId>org.springdoc</groupId>
  <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
  <version>2.0.2</version>
</dependency>

then inside application.properties :

# swagger-ui custom path
springdoc.swagger-ui.path=/swagger-ui.html

And don't forget to clean maven in case and restart your app

Then go to : http://server:port/context-path/swagger-ui.html

exemple : http://localhost:8080/swagger-ui/index.html