Search code examples
javaswaggeropenapiquarkusmicroprofile

Inherit required fields from parent class @Schema annotation


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.


Solution

  • I solved this problem by using @NotNull (or @NotBlank on strings) annotation from jakarta.validation.constraints package. Fields with these annotations are then described in schema with correct constraints automatically.

    Example:

    import jakarta.validation.constraints.NotBlank;
    
    public class ArrangementDto {
      @NotBlank private String id;
    }
    
    public class CreditCardDto extends ArrangementDto {
      private String number;
    }