[英]How can I generate an openapi definition which supports a polymorphic request body, and can generate client and server stubs accordingly?
假设我有一个 Spring 引导 REST API 定义了以下端点和模型(为简洁起见省略了获取器/设置器)
@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 规范中表达这一点,以便生成器既可以
进行设置并尝试使用 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 生成器时,inheritance 信息似乎会丢失,并且会生成像“BarWidgetAllOf”这样的奇怪类。 这是对 OAS 规范表达能力的限制,还是只是对生成器实现的限制(我已经尝试过使用 swagger-codegen 和 openapitools 生成器)?
生成的 OpenAPI 规范对于您的代码是正确的。
这不是限制,但需要有常用的默认生成。
如果您想更好地控制生成的规范,您可以 swagger @Schema 注释(不使用 JsonSubTypes),如这两个问题示例中所述:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.