Search code examples
javaopenapiswagger-uispringdoc

Springdoc OpenAPI add Classpath Yaml


I have an OpenAPI description defined in its own library.

This library is used as a gradle dependency in my project.

I am using Springdoc v.2.5.0.

My project is a Spring Cloud Gateway.

Currently, I am trying to start Swagger-UI and use the existing Openapi.yml that is inside the resources folder of the library. But in the application.yml I can't specify the yaml file directly.

"classpath:/openapi.yml" for example doesn't work, Swagger-UI can't access it that way.

So I looked into writing a Configuration Bean, as I can easily access the yaml file in Java directly, but can't find any way to pass the file to Springdoc or Swagger-UI.

Does anyone know how to do it?


Solution

  • You can just create a bean to read the yaml file and convert it to an openApi obj.

    @Configuration
    public class OpenApiConfig {
    
        @Bean
        public OpenAPI customOpenAPI() throws IOException {
            Resource resource = new ClassPathResource("../../example.yaml");
            String openApiYaml = StreamUtils.copyToString(resource.getInputStream(), StandardCharsets.UTF_8);
            OpenAPI openAPI = Yaml.mapper().readValue(openApiYaml, OpenAPI.class);
            return openAPI;
        }
    }
    

    also you need these properties in order for spring doc to be enabled

    springdoc.api-docs.path=/v3/api-docs
    springdoc.swagger-ui.path=/swagger-ui.html