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.
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);
}
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 NullpointerExceptionWhen 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
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
) {...
© 2022 - 2024 — McMap. All rights reserved.
@ApiParam
annotation in addition to the Spring annotations? – Jarv@Parameter
isn't a spring annotation, so not sure how that should be handled. You should be using@RequestParam
which is a Spring MVC annotation. – Nonna