1

I am using swagger 3.0.0-Snapshot to create documentation for my Spring Boot application. My maven dependencies are

<dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>3.0.0-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>3.0.0-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-spring-webmvc</artifactId>
            <version>3.0.0-SNAPSHOT</version>
        </dependency>

My swagger config class is as simple as possible:

@Configuration
@EnableSwagger2WebMvc
public class SwaggerConfig {
    @Bean
    public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
                .useDefaultResponseMessages(false)
                .select()
         .apis(RequestHandlerSelectors.basePackage("com.mycompany.cs"))
                .paths(PathSelectors.any())
                .build()
                .pathMapping("/")
                .useDefaultResponseMessages(false);
    }

And my controller method has the following annotation:

@ApiOperation(value = "Hello world", httpMethod = "POST")
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "OK",
                    examples = @Example(value = @ExampleProperty(mediaType = "application/json",
                            value = exampleValue)))
    })

It is working and shows in Swagger UI "Example Value" field value that has constant string exampleValue that is private static String.

The question is how to pass the content of json file that is in resources folder to @ExampleProperty value?

I tried to read file content in static block and pass it to initialize final String with it, but then the compiler says that "Attribute value has to be constant".

The content of json file must be shown in example field in Swagger UI.

  • where are you getting 3.0.0-SNAPSHOT? I only see up to version 2.9.2 in maven central. The value = @ExampleProperty(mediaType = "application/json", value = exampleValue))). is not displaying in the UI for me. – user6811616 Apr 01 '20 at 14:54

1 Answers1

2

Good news is that Swagger is using Spring and it is possible to use the power of DI.

For instance, you want to add new functionality to ServiceModelToSwagger2MapperImpl. Create your own component that extends it and mark it primary. Spring will autowire your implementation of ServiceModelToSwagger2Mapper abstract class.

@Component
@Primary
@Slf4j
public class ServiceModelToSwagger2MapperExtensionImpl extends ServiceModelToSwagger2MapperImpl {

For instance, you want it to read the content of the file and put it to the example field:

@Override
protected Map<String, Response> mapResponseMessages(Set<ResponseMessage> from) {
    Map<String, Response> responses = super.mapResponseMessages(from);
    responses.forEach((key, response)-> {
        Map<String, Object> examples = response.getExamples();
        examples.entrySet().forEach(example -> {
            Object exampleObject = example.getValue();
            if (exampleObject instanceof String) {
                String exampleValue = (String) exampleObject;
                if (exampleValue.startsWith("file:")) {
                    String fileContent = readFileContent(exampleValue);
                    example.setValue(fileContent);
                }
            }});
    });

    return responses;
}

private String readFileContent(String example) {
    String fileContent = "";
    try {
        String fileName = example.replace("file:", "");
        File resource = new ClassPathResource(fileName).getFile();
        if(resource.exists()) {
            fileContent
                    = new String(Files.readAllBytes(resource.toPath()));
        }
    } catch (
            IOException e) {
        log.error("Cannot read swagger documentation from file {}", example);
    }
    return fileContent;
}

And here is an example of usage in your controller:

@ApiResponses(value = {
        @ApiResponse(code = 200, message = "OK",
                examples = @Example(value = @ExampleProperty(mediaType = "application/vnd.siren+json",
                        value = "file:/data/controller-responses/reponse.json")))
})
  • 2
    How to do this with swagger 3.0? – Robin Dijkhof Feb 18 '21 at 15:39
  • Is there any way to add the resources file content to the `@ExampleObject`? I am trying to add the `@ExampleObject` from the `resources file` using `ref` but its not working for some reason. I have posted my question: https://stackoverflow.com/q/71616547/7584240 – BATMAN_2008 Mar 30 '22 at 20:32
  • @BATMAN_2008 were you able to find the solution? – Jimmy Apr 01 '22 at 14:52
  • @Jimmy Thanks a lot for reaching out. No, I am still looking for some suggestions. I have got one response but that's also not working. Here is the question and answer: https://stackoverflow.com/q/71687744/7584240. Please let me know if something can be done for this issue. – BATMAN_2008 Apr 01 '22 at 15:19
  • @BATMAN_2008 I check that thread and I think I have a better answer than the posted one. If you think that is better please accept it. Thanks – Jimmy Apr 03 '22 at 15:41