Bashir Zamani
Bashir Zamani

Reputation: 150

@Parameter(required = false) not working in swagger open api v3

my project is java spring boot 2 with maven . I use springdoc-openapi-ui dependency. problem is @Parameter(required = false) not working on my api params. enter image description here

enter image description here

Upvotes: 10

Views: 22458

Answers (3)

Silas Caimi
Silas Caimi

Reputation: 41

I analyzed the options reported above and came to the following conclusions

Both @RequestParam(required = false) and @Nullable result in the same behavior in the swagger documentation by removing the *required, however the behavior is different in the application:

  • Using @RequestParam(required = false) makes the method more descriptive but if the object is not passed it will be null. This requires handling to avoid NullpointerException

  • When using @Nullable, if the object is not passed, an instance of the object is still received with all attributes as null, in this case not requiring treatment

In my case I chose to use @Nullable in the interface to keep the default behavior

Upvotes: 2

Anton Lukyanau
Anton Lukyanau

Reputation: 11

I had the same problem. My solution is add jakarta.annotation.@Nullable for non required parameters.

public ResponseEntity<?> getAllByMonthAndYear(
        @Nullable @RequestParam("month") Integer month,
        @Nullable @RequestParam("year") Integer year
) {...

Upvotes: 1

Milad Amery
Milad Amery

Reputation: 386

I don't know how much of swagger annotations Springdoc-openapi supports but according to its own example at PetApiDemo in /findByStatus or /findByTags endpoints you can see by applying @RequestParam(required = false) which is a Spring Annotation! a parameter has become optional.

import org.springframework.web.bind.annotation.RequestParam;
default ResponseEntity<List<Pet>> findPetsByStatus(
        @Parameter(
                explode = Explode.TRUE, 
                name = "status", 
                in = ParameterIn.QUERY, 
                description = "Status values that need to be considered for filter", 
                style = ParameterStyle.FORM, 
                schema = @Schema(
                        type = "string", defaultValue = "available", 
                        allowableValues = {"available", "pending", "sold"}
                )
        )
        @Valid @RequestParam(value = "status", required = false)
        List<String> status) {
    return getDelegate().findPetsByStatus(status);
}

Upvotes: 16

Related Questions