我需要指定我的端点具有一个必填字段,一个可选字段,并且可以打开任意数量的字段(无需验证即可发送)。
例如端点/user
user_id: str, mandatory
timestamp_utc: timestamp, optional
..*accept_any_extra_fields**..
因此,如果有人将以下json发送到我的端点,则端点应接受
{ "user_id": 1,
"name": "Sam",
"location": "USA"
}
,但是如果发送以下json失败,因为它不包含user_id
。
{ "name": "Sam",
"location": "USA"
}
它应该失败。
我是OpenAPI / Swagger的新手。我知道我可以发送额外的数据。但是我如何将其描述为有关OpenAPI的文档,以便一个人(或一个程序)知道他们可以发送任何字段(例如名称,位置)以及user_id
答案 0 :(得分:1)
additionalProperties
关键字允许模式具有properties
部分中列出的属性以外的其他属性。
MyModel:
type: object
required:
- user_id
properties:
user_id:
type: string
timestamp_utc:
type: string
additionalProperties: true # OpenAPI 3.0
# or
# additionalProperties: {} # OpenAPI 2.0
实际上,在没有additionalProperties
关键字的情况下,OpenAPI模式是open to extension by default。但是,某些工具认为缺少additionalProperties
是“不允许的其他属性”,因此最好以显着方式添加additionalProperties: true
/ additionalProperties: {}
,以防万一。
如果额外属性仅限于特定数据类型,例如string
,使用
additionalProperties:
type: string
答案 1 :(得分:1)
您使用Java-Spring吗?我在Spring控制器的注释方法中使用Swagger,在Java代码中,您可以通过以下方式指定所需的参数:
@ApiOperation(value = "Get user", notes = "Get a user by the given filters")
@GetMapping("v1/users")
public UserDTO getUsers(@ApiParam(value = "User id", required = true)
@RequestParam(value = "user_id", required = true) String userId,
@ApiParam(value = "Date", required = false)
@RequestParam(value = "timestamp_utc", required = false)
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime utc,
@ApiParam(value = "Some other", required = false)
@RequestParam(value = "some_other", required = false) String someOther){
return service.getUser(userId, utc, someOther);
}
@ApiOperation注释是为了描述您的身份。
@ApiParam注释用于描述参数特征,而所需的属性用于告知参数。
别忘了添加招摇的依赖项,here在行家中。
您还可以在YAML中生成API文档。一个示例是here。请检查用户/登录端点。
希望我的回答对您有所帮助。