Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swagger UI with swagger.yaml in SpringBoot

We have a SpringBoot (version 1.5.12) REST Api with springfox-swagger2 and springfox-swagger-ui (version 2.9.2)

@EnableSwagger2
public class Application extends SpringBootServletInitializer {
   @Bean
   public Docket swagger() {
       return new Docket(SWAGGER_2)
            .select()
            .apis(RequestHandlerSelectors.any())
            .paths(PathSelectors.any())
            .build();
    }

I can see the Swagger UI at http://localhost:8080/swagger-ui.html

How can I configure swagger-ui to read my swagger.yaml/json configuration file instead to generate it automatically? I tried several configuration without success.

like image 575
Fabry Avatar asked May 08 '19 15:05

Fabry


People also ask

How do I load a YAML file in Swagger UI?

Simply drag and drop your OpenAPI JSON or YAML document into the Swagger Editor browser window. File → Import URL. Paste the URL to your OpenAPI document.

Does swagger support YAML?

Swagger definitions can be written in JSON or YAML. In this guide, we only use YAML examples, but JSON works equally well. A sample Swagger specification written in YAML looks like: swagger: "2.0"

How do I enable Swagger UI in spring boot project?

To enable the Swagger2 in Spring Boot application, you need to add the following dependencies in our build configurations file. For Gradle users, add the following dependencies in your build. gradle file. Now, add the @EnableSwagger2 annotation in your main Spring Boot application.


1 Answers

You need to create a class which can provide a SwaggerResourcesProvider @Primary bean, which specifies the location of the config as below (considering the swagger.json file is present in src/main/resources)

@Configuration
public class SwaggerSpecConfig {

    @Primary
    @Bean
    public SwaggerResourcesProvider swaggerResourcesProvider(InMemorySwaggerResourcesProvider defaultResourcesProvider) {
        return () -> {
            SwaggerResource wsResource = new SwaggerResource();
            wsResource.setName("new spec");
            wsResource.setSwaggerVersion("2.0");
            wsResource.setLocation("/swagger.json");

            List<SwaggerResource> resources = new ArrayList<>(defaultResourcesProvider.get());
            resources.add(wsResource);
            return resources;
        };
    }
}

Then on the Swagger UI, you'll be able to select the spec from your json (named as new spec here) as below:

enter image description here

Here's a link to the Springfox documentation: http://springfox.github.io/springfox/docs/current/#aggregating-multiple-swagger-specifications-in-the-same-swagger-ui

like image 76
Madhu Bhat Avatar answered Oct 14 '22 07:10

Madhu Bhat