How can I manually describe an example input for a java @RequestBody Map<String, String>?

Josh J picture Josh J · Jan 25, 2017 · Viewed 9.1k times · Source

I am designing an api where one of the POST methods that takes a Map<String, String> of any key value pairs.

@RequestMapping(value = "/start", method = RequestMethod.POST)
public void startProcess(
    @ApiParam(examples = @Example(value = {
        @ExampleProperty(
            mediaType="application/json",
            value = "{\"userId\":\"1234\",\"userName\":\"JoshJ\"}"
        )
    }))
    @RequestBody(required = false) Map<String, String> fields) {
    // .. does stuff
}

I would like to provide an example input for fields but I can't seem to get it to render in the swagger output. Is this not the correct way to use @Example?

Answer

Michael Lihs picture Michael Lihs · Oct 3, 2018

The issues mentioned in @g00glen00b's answer seems to be fixed. Here is a code snippet of how it can be done.

In your controller class:

// omitted other annotations
@ApiImplicitParams(
        @ApiImplicitParam(
                name = "body",
                dataType = "ApplicationProperties",
                examples = @Example(
                        @ExampleProperty(
                                mediaType = "application/json",
                                value = "{\"applicationName\":\"application-name\"}"
                        )
                )
        )
)
public Application updateApplicationName(
        @RequestBody Map<String, String> body
) {
    // ...
}

// Helper class for Swagger documentation - see http://springfox.github.io/springfox/docs/snapshot/#q27
public static class ApplicationProperties {

    private String applicationName;

    public String getApplicationName() {
        return applicationName;
    }

    public void setApplicationName(String applicationName) {
        this.applicationName = applicationName;
    }

}

Additionally, you need to add the following line to your Swagger config:

// omitted other imports...
import com.fasterxml.classmate.TypeResolver;

@Bean
public Docket api(TypeResolver resolver) {
    return new Docket(DocumentationType.SWAGGER_2)
            .select()
            .apis(RequestHandlerSelectors.any())
            .paths(PathSelectors.any())
            .build()
            .apiInfo(apiInfo())
            // the following line is important!
            .additionalModels(resolver.resolve(DashboardController.ApplicationProperties.class));
}

Further documentation can be found here: http://springfox.github.io/springfox/docs/snapshot/#q27