cloudwalker
cloudwalker

Reputation: 2466

Validating input parameters for JAX-RS methods

I'm writing a JAX-RS API, and am using the Response class as the return type of each method. However, I'm trying to figure out the "best" approach to validate parameters.

I've written some REST APIs before, and would usually have custom validation routines in the method and then have a custom return object with validation messages in it. I'm thinking I want to do the same here, but is that "preferred"?

I know there are annotations like @NotNull, etc. that you can apply and provide custom validation messages, but I don't really like the way that ends up looking.

So, what I did is that I wrote a return object bean that I'm using as the .entity() for my JAX-RS response, and I'm putting all of my validation messages in there. I use the same return object for Successes and Failures, but it's just a matter of which parameters I populate in there depending on the scenario. This is an internal API, so there won't be any external consumers. I just wanted to standardize the return type so it always returns the same "object".

Does that sound like a good approach? I'm a little rusty on REST API best practices, and I've been googling around like crazy but haven't really come to any best practices conclusions.

Upvotes: 2

Views: 1314

Answers (1)

LeTex
LeTex

Reputation: 1452

Input validation for RestAPI is not straight forward. There are a lot of internet resources, but none covers an elegant way of doing this.

As you mentioned the trivial input validations can be done using the annotation of different implementations of jax-rs library. These annotations can be sophisticated as regex is supported. Which will help you cover more validation cases than @NotNull, @size , etc. Theses annotations also accept message as input, which will help you customize a message that has to be returned to a user.

Those annotations may not look sexy (specially when regex is involved); but I would still prefer it over writing my own validator.

The other concern of validation which is a little bit tricky is when you want to validate constraints (more like a logic),

say for example you have this requirement: if parameter A has value X, Parameter B must have not be empty, otherwise it is OK to have parameter B empty. This is not something you could handle using the usual javax.validation.constraints.*. I didn't find a good library that could handle this.

take a look at

javax.validation.ConstraintViolation 

you could write your own custom validation logic that will be called whenever the library intercepts call to your API.

Upvotes: 1

Related Questions