Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 860
IchBinGrumpig Avatar asked Feb 17 '19 23:02

IchBinGrumpig


1 Answers

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;
  }
}
like image 75
Wobbley Avatar answered Sep 23 '22 16:09

Wobbley