【发布时间】:2022-12-01 11:10:43
【问题描述】:
使用 oneOf 的 OpenAPI 鉴别器
使用具有 openApi 规范的鉴别器并使用 Spectral 进行 linting 的最小示例。
错误信息:
~/git/openapi_discriminator/openapi/v1/api.yaml
22:23 error oas3-valid-media-example "example" property must match exactly one schema in oneOf paths./discriminatortest.get.responses[200].content.application/json.example
背景
具有简单 GET 方法的 OpenAPI 模式,可以返回不同类型的 Animal。
定义了 Animal 的子类,它可以是 Chicken 或 Dog。
Animals 唯一的属性是 legs。
鉴别器用于区分 Chicken 或 Dog,其中 Chicken 有 two legs 和 Dog 有 four 腿。
目标
我要验证请求响应中的示例是否只匹配一个模式。
问题
我认为使用鉴别器可能意味着带有twolegs的任何东西都是Chicken,而带有fourlegs的任何东西都是Dog。
我是不是弄错了,Dog拥有twolegs仍然是合法的,这就是它出错的原因?
我可以将其更改为anyOf,但鉴别器就没有用了吗?
代码
代码回购 - openapi_discriminator
openapi_discriminator/openapi/v1/api.yaml:
openapi: "3.0.3"
info:
title: Open API Discriminator Example
version: "v1"
tags:
- name: discriminator
paths:
/discriminatortest:
get:
tags:
- discriminator
summary: Example using discriminator
description: "Demonstrate a minimal example"
responses:
"200":
description: Created
content:
application/json:
schema: {$ref: "schemas.yaml#/components/schemas/Animal"}
example:
legs: "two"
openapi_discriminator/openapi/v1/schemas.yaml:
openapi: "3.0.3"
components:
schemas:
Animal:
type: object
discriminator:
propertyName: legs
mapping:
two: Chicken
four: Dog
oneOf:
- $ref: '#/components/schemas/Dog'
- $ref: '#/components/schemas/Chicken'
Chicken:
type: object
required:
- legs
properties:
legs:
type: string
Dog:
type: object
required:
- legs
properties:
legs:
type: string
openapi_discriminator/openapi/.spectral.yml
extends: spectral:oas
rules:
info-contact: false
info-description: false
oas3-api-servers: false
openapi-tags: true
operation-tags: true
operation-operationId: false
operation-description: true
运行 linting 命令:spectral lint "openapi/v1/api.yaml" --ruleset openapi/.spectral.yml
【问题讨论】:
标签: openapi discriminator spectral