如何使用 Swagger 正确记录字符串化 JSON?

问题描述 投票:0回答:1

在与 ChatGPT 争论这个问题之后,我怀疑我想要实现的目标是不可能的,但希望还没有完全消失。

我有一个 API 端点,它返回包含 2 个字段的 JSON 响应:一个

id
(整数)、一个
event_name
(字符串)和
event_data
字段(包含 JSON 的字符串)。像这样:

{
  "id": 1,
  "event_name": "typeA",
  "event_data": "{\"action\": \"Action1\", \"value\": \"some-string\"}"
}

问题是

event_name
可以是 3 个值之一:
typeA
typeB
typeC
,基于此,会产生级联效应,就像如果它是
TypeA
那么
event_data
将具有
 action
键,可以是
Action1
Action2

我目前的方法是只记录字段:

properties:
  id:
    type: integer
  event_name:
    type: string
    enum: [TypeA, TypeB, TypeC]
  event_data:
    type: string
    format: json

并使用 ednpoint 描述来提供 `event_data 的可能值。

我想要实现的是以更加用户友好的方式在响应模式中包含 JSON 描述。如果这样的事情能够奏效那就太好了,但事实并非如此:

properties:
  id:
    type: integer
  event_name:
    type: string
    enum: [TypeA, TypeB, TypeC]
  event_data:
    type: string
    format: json
    oneOf:
      $ref: '#/components/schemas/TypeA'
      $ref: '#/components/schemas/TypeB'
      $ref: '#/components/schemas/TypeC'

components:
  schemas:
    TypeA:
      type: object
      properties:
        action:
          type: string
          enum: [Action1, Action2]
        value:
          type: string
   TypeB:
      type: object
      properties:
        ...
   TypeC:
      type: object
      properties:
        ...

有办法做到吗?

swagger openapi openai-api api-documentation
1个回答
0
投票

在 OpenAPI 3.1 中,可以使用

contentMediaType
contentSchema
关键字定义 JSON 格式的字符串。然而,对这些关键字的实际工具支持(例如用于验证/序列化/反序列化目的)可能不存在。

  event_data:
    type: string

    contentMediaType: application/json
    contentSchema:
      type: object
      required: [action, value]
      properties:
        action:
          type: string
          example: Action1
        value:
          type: string
          example: some-string
      additionalProperties: false

问题是

event_name
可以是 3 个值之一:
typeA
typeB
typeC
,基于此,会产生级联效应,就像如果它是
TypeA
那么
event_data
将具有
 action
键,可以是
Action1
Action2

我建议在模式或端点的

description
中记录这些约束。

虽然技术上可以使用

oneOf
/
anyOf
/
discriminator
/等。根据另一个属性的值来改变一个属性的
contentSchema
,这会使模式的可读性变得复杂,并且考虑到缺乏工具支持,为此烦恼没有什么意义。

© www.soinside.com 2019 - 2024. All rights reserved.