The same way that we have to validate the input of our users in a form, validating what they introduce and displaying them that they have introduced wrong some input we have to do the same in a rest api.
If we want to validate the requests that we receive in our java backend endpoint we can use javax validations annotations in our request objects.
When the backend receives a request we have to validate that the values meet the constraints.
Suppose that the user will send bad values in his request and be ready for that.
To do it we can instantiate a
ValidatorFactory and call
validate method to check that all the constraints are fulfilled.
The above code can be improved because there’s no need to instantiate the ValidatorFactory this way. We can use
@Valid annotations to do it for us. Our resource class has to be tagged with
@ValidateRequest and the parameters in the
methods with @Valid.
To use the annotations that we were talking about we need to use the following dependencies in the pom.xml file of our Java maven project.
Note that in the maven dependency we have set scope
provided. It’s important to check libraries that your application
server comes with. In case that we are using JBoss application server we have to check in the modules folder.
Use provided in the maven dependencies when your application server has the library.
If we do:
We will get a list of folders where the different libraries that come in the JBoss application server.
Once you know which libraries you have in your application server is good to use them instead of providing your own.
The good thing to use hibernate validator is that this library comes with a lot of annotations that help us validate
things in the requests that our api receives. When our API is running we get
HibernateValidatorAdapter for free,
that will check if our constraints are fulfilled.
Use the libraries and don’t reinvent the wheel writing code that has been already written
Using Exception Mappers
If we don’t provide an exception mapper our api will return a 500 Internal server error code because a
MethodConstraintViolationException is thrown
ValidatorAdapter which is not the most desired response for our clients.
It’s better in this situation to return a bad request to our clients. This is what the next mapper is doing.
Return suitable http codes to your api clients depending on each situation.
Response received when using exception mapper
Finally if we test the API and we don’t send all the parameters we receive a 400 Bad request error with a message of the value that we are missing.
In this post we have seen how to validate requests in our rest api using Java annotations. We have seen also some principals like knowing our app server libraries or sending the suitable error codes to our api clients.