“discriminator” in polymorphism, OpenAPI 2.0 (Swagger 2.0)

戏子无情 提交于 2019-11-28 11:54:25
Wilson

According to this google group, discriminator is used on top of the allOf property and it is defined in the super type for polymorphism. If discriminator is not used, the allOf keyword describes that a model contains the properties of other models for composition.

Just like in your sample code, Pet is a super type with property of petType identified as the discriminator and Cat is a sub type of Pet. Following is a json example of a Cat object:

{
  "petType": "Cat",
  "name": "‎Kitty"
}

The use of discriminator intends to indicate the property used to identify the type of an object. Assumes that there are tools that can proper support definition objects with the use of discriminator, it is possible to determine the type by scanning the property. For example, identify the object is a Cat according to petType.

However, the discriminator field is not well defined in the current version's specification or the samples (see issue #403). As far as I know, there is no tools provided by Swagger properly support it at the time being.

discriminator may be used if the model has a property used to determine the type. In this case, it is naturally fit and it can be used as an indicator for other developers understand the polymorphism relationship. If third party tools like ReDoc which support discriminator (see petType in this gif and example) is considered, you may find this useful.

The discriminator functionality has been much improved in OpenApi 3. You now provide a discriminator object which contains the name of the discriminator property, as well as a mapping of values of that property to schema names.

(I realize you did ask about OpenApi 2, but this is so much improved in 3 that hopefully you can make use of it).

See: https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#discriminatorObject for the actual spec

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!