Inherit required fields from parent class @Schema annotation

291 Views Asked by At

These are my classes for which I would like to generate openapi specification:

import org.eclipse.microprofile.openapi.annotations.media.Schema;

@Schema(requiredProperties = {"id"})
public class ArrangementDto {
  private String id;
}

public class CreditCardDto extends ArrangementDto {
  private String number;
}

This is how my generated specification looks like:

ArrangementDto:
      required:
      - id
      type: object
      properties:
        id:
          type: string

CreditCardDto:
      type: object
      properties:
        id:
          type: string
        number:
          type: string

As you can see, the information that id is required on CreditCardDto is lost. How should we solve this issue? Is there a way to inherit the required property to child classes?

I am using Quarkus 3, which uses Smallrye OpenAPI extension compliant with the MicroProfile OpenAPI specification in order to generate API OpenAPI v3 specification.

2

There are 2 best solutions below

1
On

Not sure about it, but I think that you need to use @Schema on the properties of the child class and indicate that it inherits the required property from the parent class!

Here is a sample that may help you:

@Schema(requiredProperties = {"id"})
public class ArrangementDto {

  private String id;
}

public class CreditCardDto extends ArrangementDto {

  @Schema(required = true)
  private String cardNmber;
}

This way you are confirming that the cardNumber property of the CreditCardDto is required, in addition to inheriting the id required field from the ArrangementDto class and your generated OpenAPI specification should have them now!

0
On

In Quarkus you can choose the hybrid approach for generating your openapi specification.

Meaning: you can provide a static openapi yaml file and the dynamic part from your annotations will be added to it.

See this link: https://quarkus.io/guides/openapi-swaggerui#loading-openapi-schema-from-static-files

And also check the OpenApi spec for inheritance:

https://swagger.io/docs/specification/data-models/inheritance-and-polymorphism/