我应该能够使用可选消息正文定义POST资源吗?

时间:2019-06-10 09:57:52

标签: openapi openapi-generator

我正在使用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;
  }

0 个答案:

没有答案