想要在 Swagger 中记录可选的 JSON 参数
Want to document optional JSON parameters in Swagger
我有一个 API 正在尝试使用 Swagger 进行记录。我的 API 通过 RequestBody 中的 JSON 将 POJO 作为输入,同样地,returns 将 POJO 作为 ResponseBody 中的 JSON 输入。我的 JSON 对象中的某些字段可以为空,而其他字段是必需的。我希望我的 Swagger 文档能够反映哪些字段可以为空,哪些字段是必需的。有没有一种方法可以简单地做到这一点,而无需创建可能比在文本编辑器中手动记录 API 更长的 Swagger 配置文件?
举个具体的例子,假设我有一个如下所示的 POJO:
public class pojo {
private String val1;
private String val2;
private String val3;
//getters, setters, constructors, etc.
}
假设我希望我的 Swagger 文档告诉 reader:"On request, do not send val1 (e.g. this API is a database insert and val1 corresponds to the PK of the table which is supposed to be auto-generated), val2 is optional, and val3 is required"。我该怎么做?
作为一个相关问题,我怎样才能对响应正文做类似的事情?就像,使用上面的 POJO,我怎么能说 "on response, you should expect val1 to be empty, val2 might have a value or might be null, and val3 should have a value, assuming the service was successful"?
为了在 POJO 对象中记录可选参数,可以使用 @ApiModelProperty 属性,例如:
public class pojo {
@ApiModelProperty(value = "This parameter will be ignored", required = false)
private String val1;
@ApiModelProperty(value = "This parameter is optional", required = false)
private String val2;
@ApiModelProperty(required = true)
private String val3;
//getters, setters, constructors, etc.
}
Swagger 会将这些注释考虑在内,它应该反映在文档中:
并且在 yaml API 文档中:
pojo:
type: object
required:
- val3
properties:
val1:
type: string
description: This parameter will be ignored
val2:
type: string
description: This parameter is optional
val3:
type: string
我有一个 API 正在尝试使用 Swagger 进行记录。我的 API 通过 RequestBody 中的 JSON 将 POJO 作为输入,同样地,returns 将 POJO 作为 ResponseBody 中的 JSON 输入。我的 JSON 对象中的某些字段可以为空,而其他字段是必需的。我希望我的 Swagger 文档能够反映哪些字段可以为空,哪些字段是必需的。有没有一种方法可以简单地做到这一点,而无需创建可能比在文本编辑器中手动记录 API 更长的 Swagger 配置文件?
举个具体的例子,假设我有一个如下所示的 POJO:
public class pojo {
private String val1;
private String val2;
private String val3;
//getters, setters, constructors, etc.
}
假设我希望我的 Swagger 文档告诉 reader:"On request, do not send val1 (e.g. this API is a database insert and val1 corresponds to the PK of the table which is supposed to be auto-generated), val2 is optional, and val3 is required"。我该怎么做?
作为一个相关问题,我怎样才能对响应正文做类似的事情?就像,使用上面的 POJO,我怎么能说 "on response, you should expect val1 to be empty, val2 might have a value or might be null, and val3 should have a value, assuming the service was successful"?
为了在 POJO 对象中记录可选参数,可以使用 @ApiModelProperty 属性,例如:
public class pojo {
@ApiModelProperty(value = "This parameter will be ignored", required = false)
private String val1;
@ApiModelProperty(value = "This parameter is optional", required = false)
private String val2;
@ApiModelProperty(required = true)
private String val3;
//getters, setters, constructors, etc.
}
Swagger 会将这些注释考虑在内,它应该反映在文档中:
并且在 yaml API 文档中:
pojo:
type: object
required:
- val3
properties:
val1:
type: string
description: This parameter will be ignored
val2:
type: string
description: This parameter is optional
val3:
type: string