I am currently using OpenAPI 3 (Swagger-UI) in my Spring Boot application, and I was wondering how I could specify for some APIs only that a certain field is required/optional, if I use the same model Java class for all of them.
Here is my sample:
@Getter
@Setter
@Accessors(chain = true)
@NoArgsConstructor
@JsonIgnoreProperties(ignoreUnknown = true)
public class UserRequest {
@NotEmpty(message = "{constraints.NotEmpty.message}")
private String username;
@NotEmpty(message = "{constraints.NotEmpty.message}")
private String password;
@NotEmpty(message = "{constraints.NotEmpty.message}")
private String cookie;
@NotEmpty(message = "{constraints.NotEmpty.message}")
private String csrfToken;
}
This class is used as the input request for several APIs, but only some of them will require those fields to be all mandatory (i.e. the "password" field is only required for the login API, not for the logout one).
Is there a way to use OpenAPI's annotations to highlight the required fields only for the APIs that need them?
Thank you in advance for your help.
Regards, A.M.
I think that in this class you wont be able to specify when the parameters are mandatory or not dinamically, some options are do it in the API definition (especificate mandatory parameters) or, in case of retrieve that class from the body, create a validation service to validate field values, even use DTOs to hide those fields that u don't want to set up and specify mandatory ones, in this option mapstruct will be usefull. https://mapstruct.org/
I hope this helps, greetings!
EDIT: here you are some DTO information What is a Data Transfer Object (DTO)?