如何在Swagger API中隐藏请求字段

kwvwclae  于 2022-11-06  发布在  其他
关注(0)|答案(5)|浏览(360)

我想在模型中隐藏“id”项,在java中如何做到这一点?

i1icjdpr

i1icjdpr1#

要在Swagger API v2中隐藏请求字段:

@ApiModelProperty(hidden = true) 
 private String id;

在OpenAPI v3中:

@Schema(accessMode = Schema.AccessMode.READ_ONLY)
private String id;
4dc9hkyq

4dc9hkyq2#

@JsonProperty(access = JsonProperty.Access.READ_ONLY)
@ApiModelProperty(accessMode = ApiModelProperty.AccessMode.READ_ONLY)
private String id;

另请参阅:https://github.com/springfox/springfox/issues/2816

gzszwxb4

gzszwxb43#

可以将@Hidden与Swagger Core 2.X一起使用
@隐藏--隐藏资源、操作或属性
上述链接的示例:将指定的资源、类别或Bean类型标记为隐藏,阅读/解析时略过。

@Path("/user")
@Produces({"application/json", "application/xml"})
public class HiddenAnnotatedUserResourceMethodAndData {
    UserData userData = new UserData();

    @POST
    @Hidden
    @Operation(summary = "Create user",
            description = "This can only be done by the logged in user.")
    @Path("/1")
    public Response createUser(
            @Parameter(description = "Created user object", required = true) User user) {
        userData.addUser(user);
        return Response.ok().entity("").build();
    }

    @POST
    @Operation(summary = "Create user",
            description = "This can only be done by the logged in user.")
    @Path("/2")
    public Response createUserWithHiddenBeanProperty(
            @Parameter(description = "Created user object", required = true) UserResourceBean user) {
        return Response.ok().entity("").build();
    }
}

以上输出

openapi: 3.0.1
paths:
  /user/2:
    post:
      summary: Create user
      description: This can only be done by the logged in user.
      operationId: createUserWithHiddenBeanProperty
      requestBody:
        description: Created user object
        content:
          '*/*':
            schema:
              $ref: '#/components/schemas/UserResourceBean'
        required: true
      responses:
        default:
          description: default response
components:
  schemas:
    UserResourceBean:
      type: object
      properties:
        foo:
          type: string
ogq8wdun

ogq8wdun4#

通常在这种情况下使用DTO会很有用,为每个实体定义一个DTO(这取决于您的项目,但大多数情况下可能很有用),然后使用Mapstruct将您的实体Map到DTO,反之亦然,然后在您的DTO类中,通过在您想要的每个字段上使用@JsonIgnorProperties注解,您可以省略该字段,使其不被API服务公开。

zte4gxcn

zte4gxcn5#

扩展🏻您的实体并使用@JsonIgnoreProperties

public class UserVo {

@JsonIgnoreProperties("password")
public static class Public extends User {}

@JsonIgnoreProperties("userId")
public static class Save extends User {}

@JsonIgnoreProperties("password")
public static class Update extends User {}

}

实体🏻类:

public class User implements Serializable {
private static final long serialVersionUID = 1L;

@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer userId;

// 🚨 Write only access to password default in entity
// in order to hide it for update case we will extends class behaviour 
// in our custom views

// Instead of JsonViews i use custom views (i.e UserVo) with JsonProperty
// @JsonProperty(access = JsonProperty.Access.WRITE_ONLY) 

@NotBlank
@Schema(example = "lorem1234")
@Column(name = "password")
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY) 
private String password; 

.....
}

控制🏻器类:

// See UserVo.Save in request body it serialize this class

@PostMapping(value = "/create")
public ResponseModel<User> createUser(@Valid @RequestBody UserVo.Save user) {
 // ... My dirty code comes here 🤡
}

结果🏻:

  • 易于序列化;
  • 没有单独的域类
  • 轻松隐藏Swagger模式(Swagger在添加操作时知道隐藏ID😱)

相关问题