Custom Validators in Quarkus
Quarkus is an open-source, full-stack Java framework tailored for building cloud-native, containerized applications. Engineered for the cloud, Quarkus is designed to be lightweight and fast, boasting quick startup times. This efficiency makes it ideal for developing reliable REST APIs for creating and accessing data in a containerized environment.
Data validation is always an afterthought for developers but is important to keep the data consistent and valid. REST APIs need to validate the data it receives, and Quarkus provides rich built-in support for validating REST API request objects. There are situations where we need custom validation of our data objects
Let’s consider a simple REST API example below where we have a House data object and a REST API to create a new House.
The following fields need to be validated:
number
: should be not null.street
: should not be blank.state
: should be only California (CA) and Nevada (NV).
class House {
String number;
String street;
String city;
String state;
String type;
}
And Rest API
@Path("/house")
public class HouseResource {
@POST
public String createHouse(House house) {
// Additional logic to process the house object
return "Valid house created";
}
}
Configure Quarkus Validator
Quarkus provides the Hibernate validator to perform data validation. This is a Quarkus extension and needs to be added to the project.
For Maven projects, add the dependency to the pom.xml
:
io.quarkus
quarkus-hibernate-validator
Built-In Validators
The commonly used validators are available as annotations that can be easily added to the data object. In our House data object, we need to ensure the number property should not be null, and the street should not be blank. We will use the annotations @NotNull
and @NotBlank
:
class House {
@NotNull
int number;
@NotBlank(message = "House street cannot be blank")
String street;
String city;
String state;
String type;
}
To validate the data object in a REST API, it is necessary to include the @Valid
annotation. By doing so, there is no need for manual validation, and any validation errors will result in a 400 HTTP response being returned to the caller:
@Path("/house")
public String createHouse(@Valid House house) {
return "Valid house received";
}
Custom Validation
There are several scenarios in which the default validations are insufficient, and we must implement some form of custom validation for our data. In our example, the House data is supported only in California (CA) and Nevada (NV). Let’s create a validator for this:
@Retention(RetentionPolicy.RUNTIME)
@Target({
ElementType.FIELD
})
@Constraint(validatedBy = StateValidator.class)
public @interface ValidState {
String message() default "State not supported";
Class[] payload() default {};
Class[] groups() default {};
}
Getting into the details:
- The name of the validator is
ValidState
. In the class validation, this can be used as@ValidState
. - The default error message is added to the
message()
method. - This annotation is validated by
StateValidator.class
and is linked using the@Constraint
annotation. - The
@Target
annotation indicates where the annotation might appear in the Java program. In the above case, it can be applied only toFields
. - The
@Retention
describes the retention policy for the annotation. In the above example, the annotation is retained during runtime.
The validation logic in the StateValidator
class:
public class StateValidator implements ConstraintValidator {
List states = List.of("CA", "NV");
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
return value != null && states.contains(value);
}
}
The custom validator @ValidState
can be included in the House class:
class House {
@NotNull
int number;
@NotBlank(message = "House street cannot be blank")
String street;
String city;
@ValidState
String state;
String type;
}
Testing
In software development, unit testing is a crucial component that offers several benefits, such as enhancing code quality and detecting defects early in the development cycle. The Quarkus framework provides a variety of tools to help developers with unit testing.
Unit testing the custom validator is simple as Quarkus allows us to inject the validator and perform manual validation on the House object:
@QuarkusTest
public class HouseResourceTest {
@Inject
Validator validator;
@Test
public void testValidState() {
House h = new House();
h.state = "CA";
h.number = 1;
h.street = "street1";
Set> violations = validator.validate(h);
System.out.println("Res " + violations);
assertEquals(violations.size(), 0);
}
@Test
public void testInvalidState() {
House h = new House();
h.state = "WA";
h.number = 1;
Set> violations = validator.validate(h);
assertEquals(violations.size(), 1);
assertEquals(violations.iterator().next().getMessage(), "State not supported");
}
}
Conclusion
Quarkus is a powerful and well-structured framework that offers a range of built-in validations and supports the addition of custom validations. Validators provide a clean and convenient method for performing REST API validation, aligning with the DRY (Don't Repeat Yourself) principle. In microservices architecture, validation becomes increasingly important as each service defines and requires the validation of the data it processes. This article outlines the process of using both built-in and custom validators in Quarkus.