javaspring-bootapiswagger-uijolt

How to hide/ignore a field in swagger docs but set via spec/jolt file in spring-boot?


While writing an API that takes a model such as:

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Plan
{
  @NotBlank
  private String param1;
  private String param2;
}

I want to hide/ignore this param2 in Swagger UI. I have used @JsonIgnore, this works for swagger UI but it considers my param2 as null when it is mapped in a spec file.

I have also tried using @ApiModelProperty(accessMode = ApiModelProperty.AccessMode.READ_ONLY), @ApiParam(hidden=true) it sets the param2 via jolt spec file but doesn't hide them in Swagger UI.

In short, these are the 2 things that I am trying to achieve:

  1. Hide field param2 in Swagger UI.
  2. At the same time, set param2 via jolt mapping in the spec file.

I have tried https://www.baeldung.com/spring-swagger-hide-field these solutions and none of them seems to work. Is it possible?


Solution

  • Fix dependency

    The dependency I was using was incompatible with some versions. After some research, I found a dependency that can hide a model attribute in Swagger-UI but doesn't interrupt any other flows (i.e: Mapping via jolt file). In your pom.xml:

    <dependency>
      <groupId>io.swagger.core.v3</groupId>
      <artifactId>swagger-jaxrs2</artifactId>
      <version>2.1.6</version>
    </dependency>
    

    Hide parameter via @Schema

    In your model class, import:

    import io.swagger.v3.oas.annotations.media.Schema;
    

    and above the parameter, write:

    @Schema(hidden = true)
    

    The model class would look like this:

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public class Plan
    {
      @NotBlank
      private String param1;
      @Schema(hidden = true)
      private String param2;
    }
    

    This would hide the param2 in Swagger-UI and you can still have access to setters/getters, and your other flows will remain uninterrupted.