In my last project I've done a controller like this one:
@GetMapping("/search")
fun findByUserContact(@RequestBody @Valid userContactDto: UserContactDto) =
userService.findByUserContact(userContactDto)
An UserContactDto
is:
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type")
@JsonSubTypes(
JsonSubTypes.Type(value = Email::class, name = "email"),
JsonSubTypes.Type(value = Cellphone::class, name = "cellphone"),
JsonSubTypes.Type(value = Both::class, name = "both")
)
sealed class UserContactDto
data class Email(@field:javax.validation.constraints.Email val email: String) : UserContactDto()
data class Cellphone(@field:PhoneNumber val cellphone: String) : UserContactDto()
data class Both(
@field:javax.validation.constraints.Email val email: String,
@field:PhoneNumber val cellphone: String
) : UserContactDto()
I've design the API in this way because I don't know if the search will be done through:
- email only
- cellphone only
- both email and cellphone
but I think that is not a good design for a REST API... a GET request with a body. What could be a good approach to solve my use case?
Could a custom serializer query params -> UserContact
be a valid approach?
Will it be cleaner to create different APIs for the 3 different cases?
Thanks, Francesco