我正在使用 OpenApi3 来定义我的 API,并使用https://mvnrepository.com/artifact/org.openapitools/openapi-generator-gradle-plugin从 api 定义中生成 spring REST 控制器和模型。
我想要一个将可选请求正文作为 JSON 的端点。一个简化的例子:
/foo/{id}/bar:
post: # ok
parameters:
- in: path
name: id
schema:
type: string
requestBody:
required: false
content:
application/json:
schema:
type: object
properties:
bazuu:
type: string
responses:
'200':
description: ok
根据https://swagger.io/docs/specification/describing-request-body/,
默认情况下,请求正文是可选的
我仍然投入了额外的精力required: false
来尝试使这个请求正文成为可选的(徒劳的)。尝试在没有请求正文的情况下调用此端点会导致:
org.springframework.http.converter.HttpMessageNotReadableException: Required request body is missing: public org.springframework.http.ResponseEntity<java.lang.Void> org.my.restapi.openapi.FooApiController.fooIdBarPost(java.lang.String,org.my.restapi.openapi.model.InlineObject11)
这是因为生成器将 bazuu 参数创建为@Valid @RequestBody InlineObject11 inlineObject11
. 如果我手动将 RequestBody-annotation 更改为 required=false,我的端点也会接受没有正文的请求。
手动更正一个:
@ApiOperation(value = "", nickname = "fooIdBarPost", notes = "", authorizations = {
@Authorization(value = "ApiKeyAuth")
}, tags={ })
@ApiResponses(value = {
@ApiResponse(code = 200, message = "ok") })
@RequestMapping(value = "/foo/{id}/bar",
consumes = { "application/json" },
method = RequestMethod.POST)
default ResponseEntity<Void> fooIdBarPost(@ApiParam(value = "",required=true) @PathVariable("id") String id,@ApiParam(value = "" ) @Valid @RequestBody(required = false) InlineObject11 inlineObject11) {
return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED);
}
和包装类
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.SpringCodegen", date = "2019-06-10T12:43:04.880+03:00[Europe/Helsinki]")
public class InlineObject11 {
@JsonProperty("bazuu")
private String bazuu;
public InlineObject11 bazuu(String bazuu) {
this.bazuu = bazuu;
return this;
}