如何生成支持多态请求主体的openapi定义,并相应地生成客户端和服务器存根?

问题描述

假设我有一个Spring Boot REST API,其中定义了以下端点和模型(为简便起见,省略了getter / setter)

@JsonTypeInfo( property = "type",include = JsonTypeInfo.As.PROPERTY,use = JsonTypeInfo.Id.NAME )
@JsonSubTypes( { @JsonSubTypes.Type( FooWidget.class ),@JsonSubTypes.Type( BarWidget.class ) } )
public interface Widget {}

public class BarWidget implements Widget { private String bar; }

public class FooWidget implements Widget { private String foo; }

public class WidgetGroup
{
    private List<Widget> widgets;
}

@RestController
public class WidgetController
{
    @PostMapping( "/widgets" )
    public void createWidgets( @RequestBody WidgetGroup widgets )
    {
    }
}

是否可以在OpenAPI规范中表达这一点,以便生成器可以同时实现

  • 将以上代码复制为服务器存根和模型
  • 产生一个能够正确表示模型和API的Javascript客户端

已进行了设置,并尝试使用springdoc和springfox从代码中生成规范,然后我无法撤消该过程-上面的代码通过Springdoc生成了以下规范:

openapi: 3.0.1
info:
  title: OpenAPI definition
  version: v0
servers:
  - url: 'http://localhost:8080'
    description: Generated server url
paths:
  /widgets:
    post:
      tags:
        - widget-controller
      operationId: createWidgets
      requestBody:
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/WidgetGroup'
        required: true
      responses:
        '200':
          description: OK
components:
  schemas:
    BarWidget:
      type: object
      allOf:
        - $ref: '#/components/schemas/Widget'
        - type: object
          properties:
            bar:
              type: string
    FooWidget:
      type: object
      allOf:
        - $ref: '#/components/schemas/Widget'
        - type: object
          properties:
            foo:
              type: string
    Widget:
      required:
        - type
      type: object
      properties:
        type:
          type: string
      discriminator:
        propertyName: type
    WidgetGroup:
      type: object
      properties:
        widgets:
          type: array
          items:
            oneOf:
              - $ref: '#/components/schemas/BarWidget'
              - $ref: '#/components/schemas/FooWidget'

同时使用Java和Javascript生成器时,继承信息似乎丢失,并且会生成诸如“ BarWidgetAllOf”之类的奇数类。这是对OAS规范表达能力的限制,还是对生成器实现的限制(我已经尝试过swagger-codegen和openapitools生成器)?

解决方法

关于您的代码,生成的OpenAPI规范是正确的。

这不是一个限制,但是需要使用通常使用的默认生成。

如果要更好地控制所生成的规范,可以使用@Schema批注(不使用JsonSubTypes),如这两个示例中所述:

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...