3
votes

I have a Spring Boot (kotlin) project for which I use springdoc-openapi to generate OpenApi 3 spec. My data model looks like so:

open class Animal
data class Cat(val catName: String) : Animal()
data class Dog(val dogName: String) : Animal()

open class Food<T : Animal>
class CatFood : Food<Cat>()
class DogFood : Food<Dog>()

and a simple controller like so:

@GetMapping("/test")
fun test(): Food<out Animal> = DogFood()

for which the generated yaml is:

openapi: 3.0.1
info:
  title: OpenAPI definition
  version: v0
servers:
- url: http://localhost:8085
paths:
  /test:
    get:
      tags:
      - test-controller
      operationId: test
      responses:
        "200":
          description: default response
          content:
            '*/*':
              schema:
                $ref: '#/components/schemas/FoodAnimal'
components:
  schemas:
    FoodAnimal:
      type: object

The problem here is that my controller can return either DogFood or CatFood, and that is specified in the return type. The schema I would expect to be generated is:

openapi: 3.0.1
info:
  title: OpenAPI definition
  version: v0
servers:
- url: http://localhost:8085
paths:
  /test:
    get:
      tags:
      - test-controller
      operationId: test
      responses:
        "200":
          description: default response
          content:
            '*/*':
              schema:
                oneOf:
                  - $ref: '#/components/schemas/FoodAnimal'
                  - $ref: '#/components/schemas/DogFood'
                  - $ref: '#/components/schemas/CatFood'

components:
  schemas:
    FoodAnimal:
      type: object
    CatFood:
      allOf:
        - $ref: '#/components/schemas/FoodAnimal'
      type: object
    DogFood:
      allOf:
        - $ref: '#/components/schemas/FoodAnimal'
      type: object

Is there some way to achieve this?

2

2 Answers

11
votes

For inheritance, you just need to add @Schema annotation, on your parent class:

@Schema(
        type = "object",
        title = "Food",
        subTypes = [CatFood::class, DogFood::class]
)
open class Food<T : Animal>
class CatFood : Food<Cat>()
class DogFood : Food<Dog>()

If you need a reponse using oneOf, you will have to add @Response:

@GetMapping("/test")
@ApiResponse(content = [Content(mediaType = "*/*", schema = Schema(oneOf = [Food::class, CatFood::class,DogFood::class]))])
fun test(): Food<out Animal> = DogFood()
1
votes

I had problems using OpenApi with inheritance for nested properties.

I used JsonSubtype annotations and generics as a workaround.

data class AnimalResponse<FoodResponse>(
    val id: UUID,
    val eats: FoodResponse
)

@JsonSubTypes(value = [
    JsonSubTypes.Type(
        value = CatFoodResponse::class,
        name = "CAT_FOOD"
    ), JsonSubTypes.Type(
        value = DogFoodResponse::class,
        name = "DOG_FOOD"
    )])
interface FoodResponse

This will show all types of FoodResponses in AnimalResponse Schema.