How to customize example values in Springfox's Swagger 2 for a JSONObject request body?

IchBinGrumpig picture IchBinGrumpig · Feb 18, 2019 · Viewed 8k times · Source

I would like to customize the example values for my API documentation I am making with Springfox's Swagger (Spring REST API).enter image description here

Since the request body is a stringified JSON via JQuery AJAX, the @RequestParam is a String. I've tried multiple "solutions" including @ApiModel and @ApiImplicitParams, all of which have not worked. The "string" never seems to change.

How can I change the example values? I don't mind if that needs to be done manually. I just want the area to show a JSON object.

Answer

Wobbley picture Wobbley · Apr 24, 2019

If you are using an object to describe the request body, you can use @ApiModelProperty, example:

data class RequestBody(
    @ApiModelProperty(example = "John Doe")
    val name: String,
    @ApiModelProperty(example = "Coolstreet 1")
    val address: String
)

The alternative is to use @Example and @ExampleProperties, but I find them much more messy. There are some examples on how to use them at the official reference doc: http://springfox.github.io/springfox/docs/current/#example-application

The provided example:

@RequestMapping(value = "/2031", method = RequestMethod.POST)
@ResponseBody
@ApiOperation(value = "/2031")
@ApiImplicitParams({
    @ApiImplicitParam(
        name = "contents",
        dataType = "CustomTypeFor2031",
        examples = @io.swagger.annotations.Example(
            value = {
                @ExampleProperty(value = "{'property': 'test'}", mediaType = "application/json")
            })) 
})
public void save(@PathVariable("keyId") String keyId,
                 @PathVariable("id") String id,
                 @RequestBody String contents 
) {
}

public static class CustomTypeFor2031 { 
  private String property;

  public String getProperty() {
    return property;
  }

  public void setProperty(String property) {
    this.property = property;
  }
}