Skip to content
Advertisement

Unable to inherit in OpenAPI 3 using allOf in java

Please find the schemas in my contract yaml file :

Foo:
  allOf:
    - $ref: "#/components/schemas/Bar"
  properties:
    ancestors:
      items:
        $ref: "#/components/schemas/Bar"
      type: array
    description:
      type: object
      additionalProperties:
        type: string
    id:
      description: id
      type: string
  type: object
Bar:
  properties:
    accessAllowed:
      items:
        type: string
      type: array
    catalog:
      type: boolean
    children:
      items:
        $ref: "#/components/schemas/Bar"
      type: array

While using swagger 2, the generated class Foo extends Bar. But after using openAPI 3 Foo isn’t extending Bar when using allOf. All it is doing is copying all the properties of Bar to Foo class.

Although now that Foo class will contain all the properties of Bar, Foo isn’t actually inheriting when we look at the java code side. Is there any way to generate the class Foo extending Bar when using OpenAPI 3 as there are many cases where one need to generate classes that inherit a parent class.

Advertisement

Answer

You need to add:

...
Bar:
  ...
  discriminator:
    propertyName: barType
    mapping:
      foo: "#/components/schemas/Foo"
  ...
...

Complete example:

Foo:
  allOf:
    - $ref: "#/components/schemas/Bar"
  properties:
    ancestors:
      items:
        $ref: "#/components/schemas/Bar"
      type: array
    description:
      type: object
      additionalProperties:
        type: string
    id:
      description: id
      type: string
  type: object
Bar:
  discriminator:
    propertyName: barType
    mapping:
      foo: "#/components/schemas/Foo"
  properties:
    accessAllowed:
      items:
        type: string
      type: array
    catalog:
      type: boolean
    children:
      items:
        $ref: "#/components/schemas/Bar"
      type: array
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement