Scrivio Interview library
CodingFoundations6 min read · updated 12 November 2026

Add Jakarta Bean Validation to a JAX-RS POST /customers method and a GET /customers?page= parameter that must be at least 1. What status code does the client get for each kind of violation by default?

We put @Valid on the CustomerRequest body parameter and constraints such as @NotBlank, @Email and @Size on its fields, and annotate the query parameter as @QueryParam("page") @Min(1) int page. With a Bean Validation provider such as Hibernate Validator integrated (built in on Jakarta EE servers, jersey-bean-validation for plain Jersey), any violation on a parameter or the request body gives 400 Bad Request by default, while a violation on a validated return value gives 500, because the server produced bad data. The default error body differs by implementation, so we usually add an ExceptionMapper<ConstraintViolationException> that returns problem details with field paths.

Why this question is asked

Every API needs input validation, and writing if statements for each field quickly becomes the largest part of a resource class. Jakarta Bean Validation lets us declare the rules on the data and have the runtime enforce them before our method runs. Interviewers ask this question to check that we know how JAX-RS integrates validation, what it needs on the classpath, and the less obvious rule about status codes. In this answer, we will recap Bean Validation, add it to the POST and GET methods, see what the client receives for each kind of violation and why, and then shape the error response ourselves.

1A Quick Recap of Bean Validation

Jakarta Bean Validation is a specification for declaring constraints with annotations: @NotNull, @NotBlank (not null and not only whitespace), @Size, @Min, @Email, @Pattern and others in jakarta.validation.constraints. A provider, almost always Hibernate Validator, implements it. @Valid means cascade: validate the constraints inside this object too. JAX-RS integrates it so that constraints on resource method parameters, and on objects marked @Valid, are checked automatically before the method is invoked.

2Adding Validation to the Two Methods

First the request DTO, with constraints on its fields. A record works well.

Java
public record CustomerRequest(
@NotBlank @Size(max = 100) String name,
@NotBlank @Email String email,
@Size(max = 20) String phone) { }
@Path("/customers")
@Produces(MediaType.APPLICATION_JSON)
public class CustomerResource {
@POST
@Consumes(MediaType.APPLICATION_JSON)
public Response create(@Valid @NotNull CustomerRequest req, @Context UriInfo uri) {
Customer c = customers.create(req);
return Response.created(uri.getAbsolutePathBuilder().path(c.id().toString()).build()).build();
}
@GET
public List<CustomerView> list(@QueryParam("page") @DefaultValue("1") @Min(1) int page) {
return customers.page(page, 50);
}
}
// POST {"name":"Ann","email":"ann@example.com"} -> 201
// POST {"name":"","email":"not-an-email"} -> 400 (two violations)
// POST with no body -> 400 (@NotNull)
// GET /customers?page=0 -> 400
// GET /customers?page=abc -> 404 (conversion failure, not validation)

Notice @NotNull next to @Valid: @Valid alone validates the object only if there is one, so an empty body would reach our method as null. And notice the last line: page=abc never reaches validation, because converting "abc" to int fails first. For a @QueryParam that fails conversion, JAX-RS returns 404, which surprises many people; if we want 400, we accept a String or a wrapper type and validate it ourselves, or map the exception.

3What Has to Be on the Classpath

The annotations do nothing without a provider and the integration. On a Jakarta EE server, Hibernate Validator and the JAX-RS integration are included, so it works out of the box. With plain Jersey on Tomcat, we add jersey-bean-validation, which brings Hibernate Validator and registers the validation feature automatically, plus an expression language implementation that Hibernate Validator uses for messages, check your version for the exact artifacts. RESTEasy has its own resteasy-validator-provider module. Spring Boot with Jersey needs spring-boot-starter-validation. If validation silently does nothing, a missing module is the first suspect.

4Why Parameters Give 400 but Return Values Give 500

The specification separates who is at fault. If a constraint on a parameter, a field of the resource, or a cascaded request body fails, the client sent bad data, so the response is 400 Bad Request. But we can also put constraints on the return value, for example @Valid on the method so the returned CustomerView is validated. If that fails, the client did nothing wrong; our server produced invalid output, so the response is 500 Internal Server Error.

Java
@GET @Path("/{id}")
@Valid // validate what we return
public CustomerView get(@PathParam("id") UUID id) { return customers.view(id); }
// If the stored customer has a blank email and CustomerView has @NotBlank email:
// -> 500, because the server is at fault
Default status by kind of violation
Where the constraint failedStatusWhy
@QueryParam, @PathParam, @HeaderParam400the client sent a bad value
request body with @Valid400the client sent a bad entity
return value with @Valid on the method500the server produced bad data
parameter that cannot be converted404 or 400, depends on the sourceconversion fails before validation
Jersey and RESTEasy follow these rules; their error bodies differ.

5Shaping the Error Response

By default, the response body for a violation depends on the implementation: Jersey sends little or nothing unless ServerProperties.BV_SEND_ERROR_IN_RESPONSE is enabled (check your version), and RESTEasy has its own report format. Clients should not depend on those. So we add an ExceptionMapper that turns violations into a consistent problem details body (RFC 9457), with a field path per error.

Java
@Provider
public class ViolationMapper implements ExceptionMapper<ConstraintViolationException> {
@Override
public Response toResponse(ConstraintViolationException e) {
List<Map<String, String>> errors = e.getConstraintViolations().stream()
.map(v -> Map.of("field", lastNodes(v.getPropertyPath()), // "email" rather than "create.req.email"
"message", v.getMessage()))
.toList();
Map<String, Object> body = Map.of(
"type", "https://example.com/problems/validation",
"title", "Invalid request", "status", 400, "errors", errors);
return Response.status(400).type("application/problem+json").entity(body).build();
}
}
// {"type":".../validation","title":"Invalid request","status":400,
// "errors":[{"field":"name","message":"must not be blank"},
// {"field":"email","message":"must be a well-formed email address"}]}

There is a catch: this mapper returns 400 for every ConstraintViolationException, including return-value violations, which should be 500. A careful mapper checks whether any violation's path contains a return value node (ElementKind.RETURN_VALUE) and returns 500 with a generic message in that case, logging the details for us instead of showing them to the client.

6Follow-up questions

What is the difference between @NotNull, @NotEmpty and @NotBlank?

@NotNull only rejects null. @NotEmpty also rejects an empty string or collection. @NotBlank, for character sequences, also rejects strings that are only whitespace, so " " fails @NotBlank but passes @NotEmpty. For required text fields, @NotBlank is usually what we mean.

Can we validate a query parameter bean?

Yes. With @BeanParam we can group parameters into a class whose fields carry @QueryParam and constraints, and mark it @Valid. Violations there also give 400.

How do you test the validation?

With an integration test against the running resource, for example JerseyTest, sending invalid bodies and parameters and asserting the status and the error fields. A unit test with a Validator from Validation.buildDefaultValidatorFactory() is quicker for the DTO rules themselves.

7Conclusion

In this answer, we added Bean Validation to a JAX-RS resource with @Valid and @NotNull on the CustomerRequest body, field constraints like @NotBlank, @Email and @Size, and @Min(1) on the page query parameter. Validation needs a provider such as Hibernate Validator, built into Jakarta EE servers and added with jersey-bean-validation for plain Jersey. Violations on parameters and the request body give 400, violations on validated return values give 500 because the server is at fault, and since default error bodies vary, an ExceptionMapper for ConstraintViolationException gives clients consistent problem details with field paths.

What to say in the interviewAbout 90 seconds aloud

Open with

On the DTO I put the constraints on the fields, for example @NotBlank and @Size max 100 on name, @NotBlank and @Email on email. On the resource method I annotate the body parameter with @Valid so the runtime cascades into it, and I add @NotNull so an empty body is rejected too.

Then, if they want more

For the list endpoint I write @QueryParam page with @DefaultValue 1 and @Min 1 on an int. This only works if a Bean Validation provider is integrated: on a Jakarta EE server it is built in, with plain Jersey I add jersey-bean-validation, which brings Hibernate Validator. For status codes, the rule is about who is at fault.

A violation on a parameter or on the request body gives 400 Bad Request. If I put @Valid on the method to validate the return value and that fails, the client gets 500, because the server produced bad data.

One gotcha is that a page value like abc fails conversion before validation, and for a query parameter JAX-RS returns 404 by default.

The default error bodies differ between Jersey and RESTEasy, and Jersey sends very little unless a server property is enabled, so I add an ExceptionMapper for ConstraintViolationException that returns problem details with the field path and message for each violation, and returns 500 for return-value violations.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Official documentation
Jakarta EE specifications
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Add Jakarta Bean Validation to a JAX-RS POST /customers method and a GET...": https://scrivio-interview-library.netlify.app/java/jax-rs/586ac522ab/