简体   繁体   中英

How to pass file content to swagger @ExampleProperty annotation value?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM