Skip to content
Tutorials Center
My learning

Topics

Lesson 12 of 36 ยท REST Endpoints

JSON and Bean Validation

Serialize records to JSON, customize Jackson in Quarkus, and validate request bodies with Bean Validation annotations, @Valid and automatic 400 responses.

Almost every REST service sends and receives JSON, and almost every service must reject bad input. Quarkus handles both with two extensions: Jackson for JSON and Hibernate Validator for Bean Validation. You add them, annotate your classes, and Quarkus connects them to the REST layer.

The real Quarkus code in this lesson is read-only. The runnable stand-ins are plain Java: a tiny reflection-based JSON writer and a tiny validator that reads annotations. They show what the libraries do under the hood.

Adding JSON support

XML
<dependency>
    <groupId>io.quarkus</groupId>
    <artifactId>quarkus-rest-jackson</artifactId>
</dependency>

With this extension on the classpath, a method that returns an object produces application/json, and a method with an unannotated object parameter reads the body as JSON. Records work well as transfer objects:

Java
public record BookDto(Long id, String title, String author, int year) {}

@Path("/books")
public class BookResource {

    @GET
    @Path("/{id}")
    public BookDto one(@RestPath long id) {
        return new BookDto(id, "Dune", "Frank Herbert", 1965);
    }

    @POST
    public BookDto create(BookDto input) {
        return new BookDto(42L, input.title(), input.author(), input.year());
    }
}

Calling GET /books/1 returns {"id":1,"title":"Dune","author":"Frank Herbert","year":1965}.

Customizing Jackson

Annotations on the DTO control the shape:

Java
import com.fasterxml.jackson.annotation.*;

@JsonInclude(JsonInclude.Include.NON_NULL)
public record BookDto(
        Long id,
        String title,
        @JsonProperty("writer") String author,
        @JsonIgnore String internalNote,
        int year) {}

For global changes, provide an ObjectMapperCustomizer bean:

Java
import io.quarkus.jackson.ObjectMapperCustomizer;
import com.fasterxml.jackson.databind.SerializationFeature;
import jakarta.inject.Singleton;

@Singleton
public class JsonSettings implements ObjectMapperCustomizer {
    @Override
    public void customize(com.fasterxml.jackson.databind.ObjectMapper mapper) {
        mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
    }
}

Quarkus already disables timestamps for dates and registers the java.time module, so LocalDate fields print as "1965-08-01" without extra work. Properties like quarkus.jackson.fail-on-unknown-properties=true tune behaviour without code.

Returning entities directly from the database is tempting but risky: lazy fields, internal columns and cycles all leak. Use DTO records at the boundary, as the Panache lessons in Hibernate ORM with Panache show.

How a writer works

Jackson inspects classes through reflection. Quarkus avoids that cost at runtime for native images by registering the types at build time, which is why DTOs used by quarkus-rest-jackson just work in a native executable. The stand-in below reads record components with reflection and writes JSON, which is the same idea in miniature.

Java Stand-in: a tiny reflection-based JSON writer

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Bean Validation

Add the validator extension:

XML
<dependency>
    <groupId>io.quarkus</groupId>
    <artifactId>quarkus-hibernate-validator</artifactId>
</dependency>

Declare rules with annotations on the fields (or record components), then tell the endpoint to check them with @Valid:

Java
import jakarta.validation.Valid;
import jakarta.validation.constraints.*;

public record NewBook(
        @NotBlank @Size(max = 120) String title,
        @NotBlank String author,
        @Min(1450) @Max(2100) int year,
        @Email String contact,
        @Pattern(regexp = "\\d{13}") String isbn) {}

@POST
public RestResponse<BookDto> create(@Valid NewBook input) {
    // runs only when the input is valid
    return RestResponse.status(201, service.create(input));
}

If validation fails, the method body never runs. Quarkus REST returns 400 Bad Request with a JSON report that lists every violated constraint. Common constraints:

Annotation Meaning
@NotNull value is not null
@NotBlank string has a non-space character
@NotEmpty string or collection is not empty
@Size(min, max) length of a string or collection
@Min, @Max numeric bounds
@Positive, @PositiveOrZero sign checks
@Email, @Pattern format checks
@Past, @Future date checks

Validation also works on method parameters of any CDI bean, not just endpoints, and on return values. Put @Valid on nested objects so their fields are checked too.

Custom constraints

When no built-in annotation fits, write your own: declare an annotation with @Constraint(validatedBy = ...) and implement ConstraintValidator<A, T>. The rest of the flow stays the same.

Validation flow

Request JSON arrives in the endpoint.
Check Each constraint is tested.
Reject Any failure gives a 400 report.
Run Valid input reaches your code.

Your method only sees valid data.

1 / 2

Rules by reflection

The stand-in below declares three constraint annotations, finds them on record components and collects violations. That is the essential loop inside Hibernate Validator.

Java Stand-in: annotation-driven validation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Writing useful error messages

Constraints take a message attribute, and messages can come from a ValidationMessages.properties file for translations. For example @NotBlank(message = "Title is required"). The next lesson shows how to turn violations into the exact error format your API promises, with exception mappers.

Validation protects your service from malformed input, but it does not replace authorization or database constraints. A valid-looking authorId can still point to a row the caller must not touch.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which extension makes a Quarkus REST method read and write JSON?

    quarkus-rest-jackson adds Jackson-based JSON support to Quarkus REST.
  2. 2. What happens when a @Valid request body violates a constraint?

    Validation runs before the method body; failures produce a 400 Bad Request.
  3. 3. Why use DTO records instead of returning database entities?

    A DTO is a stable public shape. Entities carry internal fields, lazy relations and may contain cycles.
  4. 4. What does @NotBlank check?

    @NotBlank rejects null, empty and whitespace-only strings.

Summary

  • quarkus-rest-jackson turns return values and bodies into JSON; use records as DTOs.
  • Tune Jackson with annotations, ObjectMapperCustomizer or quarkus.jackson.* properties.
  • quarkus-hibernate-validator adds constraint annotations; @Valid triggers them and failures return 400.
  • Validation applies to any CDI bean, to nested objects (with @Valid) and to custom constraints.

Next: Exception Mappers and Error Responses