Search code examples
javaspringswaggerswagger-uispringfox

SpringFox - Hide certain fields in Swagger-ui that aren't required for the call to an endpoint


I would like to know if there is any way of making SpringFox to not show all the fields of a certain entity that aren't required in the call to an specific endpoint.

For example:

Having the following entity:

public class Car {
    long id;
    String name;
    int wheels;
    String type;
    boolean canFly;
}

And the following endpoints:

@RequestMapping(method = RequestMethod.GET,
                produces = MediaType.APPLICATION_JSON_VALUE)
public Car get(@RequestParam(value = "carId", required = true) long projectId) {
    return carService.get(carId);
}

@RequestMapping(method = RequestMethod.POST,
                consumes = MediaType.APPLICATION_JSON_VALUE,
                produces = MediaType.APPLICATION_JSON_VALUE)
public Car create(@RequestBody Car car) {
    return carService.create(car);
}

@RequestMapping(method = RequestMethod.PUT,
                consumes = MediaType.APPLICATION_JSON_VALUE,
                produces = MediaType.APPLICATION_JSON_VALUE)
public Car update(@RequestBody Car car) {
    return carService.update(car);
}

The thing is that in the create Car endpoint only name and wheels are required, but in the documentation Swagger-ui shows all the fields as if they were required. I've already tried @JsonViews but Springfox does not handle them yet.

Is there any way to avoid this?


Solution

  • Use the @ApiModelProperty (from io.swagger.annotations)

    • With required you define whether the property is mandatory or optional.
    • With hidden you can hide the property in Swagger UI, however if it's set it is returned anyway.

    For example:

    public class Car {
    
        @ApiModelProperty(value = "id", required = true)
        long id;
    
        @ApiModelProperty(value = "wheels", required = true)
        int wheels;
    
        @ApiModelProperty(value = "name", hidden = true)
        String name;
    
        @ApiModelProperty(value = "type", hidden = true)
        String type;
    
        @ApiModelProperty(value = "canFly", hidden = true)
        boolean canFly;
    }
    

    Since you use the same model for request and response (with the example above) the attributes in the documentation for GET endpoint will be also hidden (keep that in mind). If you don't want such behaviour then use separate models.