Java Spring Boot OpenApi 3 - How to add @Schema for RequestBody?

1.9k Views Asked by At
@PostMapping(produces = "application/json", consumes = "application/json")
public ResponseEntity<Book> addBook(
        @RequestBody(description = "Book to add.", required = true,
                    content = @Content(
                            schema=@Schema(implementation = Book.class)))   
        @Valid Book book
) {
    return ResponseEntity.ok(bookRepository.add(Book));

}

2.

    @PostMapping(produces = "application/json", consumes = "application/json")
public ResponseEntity<BasicBook> addBook(
        @RequestBody(description = "Book to add.", required = true,
                    content = @Content(
                            schema=@Schema(allOf = BasicBook.class, oneOf = {
                                HomeScience.class, GeneralScience.class })))   
        @Valid BasicBook book
) {
    return ResponseEntity.ok(bookRepository.add(Book));

}

Above snippet 1. is working fine. In the Swagger UI I can see the RequestBody with example value where I can execute that.

but for snippet 2. when I am trying inheritance (i.e. oneOf, allOf or anyOf), this schema is not working. Only BasicBook properties are coming in (Swagger UI)RequestBody's example value.

I have tried with @Parameter also. Here is the code

3.

        @PostMapping(produces = "application/json", consumes = "application/json")
public ResponseEntity<BasicBook> addBook(
        @Parameter(required = true, description = "DTO for book.", content = {
                @Content(mediaType = "application/json", schema = @Schema(allOf = BasicBook.class, oneOf = {
                        HomeScience.class, GeneralScience.class }, discriminatorMapping = {
                                @DiscriminatorMapping(value = "HOME", schema = HomeScience.class),
                                @DiscriminatorMapping(value = "GENERAL", schema = GeneralScience.class) }, discriminatorProperty = "type")) }) 
        @RequestBody @Valid BasicBook book
) {
    return ResponseEntity.ok(bookRepository.add(Book));

}

snippet 3. also not giving desired result.

How can I use oneOf, allOf or anyOf in the RequestBody.

0

There are 0 best solutions below