Search code examples
restswaggerdocumentationopenapi

What does mapping within discriminator do in Swagger?


The explanation in the doc is not clear for me. And I see no difference after my api doc renders.
What the difference visually? At what mapping do logically? For example

MySchema:
  oneOf:
    - $ref: '#/componets/schemas/SubSchema1'
    - $ref: '#/componets/schemas/SubSchema2'
  discriminator:
    propertyName: some_property:
    mapping:
      TypeA: '#/componets/schemas/SubSchema1'
      TypeB: '#/componets/schemas/SubSchema2'

Solution

  • So if you use editor.swagger.io it won't be much of a difference. I use Redoc if I want to validate discriminator.

    Lets take a example: You want to convert a reading to your preferred unit of measurement (which is usStandard) Your request object may be looking like this -

    {
      "value": 7,
      "unitOfMeasure": {
        "type": "distance",
        "value": "km"
      }
    }
    

    So After conversion your API will return

    {
      "value": 4.3496,
      "unitOfMeasure": {
        "type": "distance",
        "value": "mi"
      }
    }
    

    So depending upon your unit of measurement type you have to use different schema.
    if type is

    1. distance then possible values km and mi
    2. volume then possible values L and gal

    So your OpenAPI spec your discriminator will use type property to determine which schema to use. Note: in that case type will be a required property within each schema.

    This is same as jackson's type

    @JsonTypeInfo(
        use = JsonTypeInfo.Id.CUSTOM,
        property = "type",
        include = JsonTypeInfo.As.EXISTING_PROPERTY)
    public abstract class UOM {
    }
    
    @JsonTypeName("distance")
    public class DistanceUOM extends UOM {
    }
    

    And jackson will use type to determine in which class it should de-serialize to.


    Created a github gist with this usecase See Here

    So how Redoc will render this (See there is one drop-down to select type)

    Type: distance

    enter image description here

    Type: volume

    enter image description here