json - 如何在 Swagger 中引用另一个模型定义的 ID

标签 json rest swagger

假设我有一个 User 和一个 UserType 模型。我想在 User 模型中添加对 UserType-ID 的引用。 swagger 文档只展示了如何引用另一个(整个)模型,而不仅仅是它的一个属性。

所以我想知道它甚至可以只引用另一个模型定义的属性。

"definitions": {
    "User": {
        "required": [
            "username",
            "typeId"
        ],
        "properties": {
            "id": {
                "type": "integer",
                "format": "int32"
            },
            "username": {
                "type": "string"
            },
            "typeId": {
                "$ref": "UserType.id" // ==> this doesn't work! and without
                                      // the ".id" part it would include all
                                      // the properties of UserType
            }
        }
    },
    "UserType": {
        "required": [
            "name"
        ],
        "properties": {
            "id": {
                "type": "integer",
                "format": "int32"
            },
            "name": {
                "type": "string"
            }
        }
    }
}

或者这根本不可能,它应该总是:
"definitions": {
    "User": {
        ...
        "properties": {
            "typeId": {
                "type": "integer",
                "format": "int32"
            }
        }
    },
    ...
}

最佳答案

在 Swagger 2.0 中,Schema Objects 不需要描述模型(与之前版本中的 Model Object 不同)。例如,如果查看“body”参数,您会发现需要将 Schema 定义为类型,但该模式也可以表示基元和数组。

对于上述问题(和评论),我建议使用以下结构:

"defintions": {
  "User": {
    "required": [
      "username",
      "typeId"
    ],
    "properties": {
      "id": {
        "type": "integer",
        "format": "int32"
      },
      "username": {
        "type": "string"
      },
      "typeId": {
        "$ref": "#/definitions/TypeId"
      }
    }
  },
  "UserType": {
    "required": [
      "name"
    ],
    "properties": {
      "id": {
        "$ref": "#/definitions/TypeId"
      },
      "name": {
        "type": "string"
      }
    }
  },
  "TypeId": {
    "type": "integer",
    "format": "int32"
  }
}

TypeId 现在已外部化,如果需要更改其定义,您可以在一处更改它。当然,您可能想添加额外的 "description"到字段和模型以更好地记录目的。

关于json - 如何在 Swagger 中引用另一个模型定义的 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26814790/

相关文章:

json - 如何解决警告 :The value 4 (type int) in a string field was converted to u'4' (type string) in Ansible?

Javascript:将值列表转换为对象集

java - Spring Boot 忽略 Rest Controller 中的 Jackson 注释

json - Java EE7 REST 服务器不再将 List<String> 作为 JSON 返回

c# - 将 curl 命令转换为 restsharp

java - 从 yaml 文件中过滤属性

jquery - fullcalendar-无法缓存 AJAX 调用的 JSON 响应

rest - 如何在Grails中将领域类作为REST资源编写集成测试?

asp.net-web-api - 标有 JsonIgnore 的属性仍显示在 Web API 的 Swagger UI 文档中

dictionary - 为什么 `additionalProperties` 是 Swagger/OpenAPI 2.0 中表示 Dictionary/Map 的方式