Home United States USA — software Akka HTTP: Another One Validation Direction

Akka HTTP: Another One Validation Direction

67
0
SHARE

Dive into model validation using Akka HTTP. See the common challenges with HTTP request validation and how to solve them and keep your data validated.
The question today is how to validate an HTTP request body using Akka HTTP directives. Of course, we can use the validate directive, but it has one drawback, which I described in my previous post about a model validation in Akka HTTP. You may want to use the require method, but it is not very functional. Today, I want to show another way to validate HTTP request bodies in Akka.
Let’s assume we have a REST endpoint that works with the following data model:
As you can see, this is a simple case class. Of course, we want to be sure that all of the data is valid, e.g. age is not negative.
So, how do we implement constraints for case class fields in the context of Akka HTTP? We just want to have a nice response for situations when some or all of the fields have invalid values. We need to send back something like this to a client:
After the problem is highlighted, a solution needs to be found for it.
Firstly, we need to declare standard data classes for the validation domain:
Then we can create a trait that contains an abstraction of validation logic:
The validationStage(rule: Boolean, fieldName: String, errorText: String) represents the smallest piece of a model validation process. It has three arguments. The first one is rule, which is responsible for some validation constraint that you want to apply to a model field. The second one is fieldName, which is needed for a validation response. The third one is errorText, which is used for a description of the validation error.
Finally here is a validation directive:
The best way to see how the directive works is to write a test or two for it. Moreover, we will ensure that it works fine. Firstly, I suggest seeing how a particular validator acts and then inject it in our Akka HTTP directives.
That’s how you can create a validator for the Contact model. Notice that if you have many models and some validation rules are common, you’d better hold them in a more general place (validation rules trait or object).
What about testing?
Ok.
Now we see that the validator works as expected. It’s time to see it in action in the context of Akka HTTP.
And do not forget to handle ModelValidationRejection .
Well, I presented a solution to handle a model (case classes) in Akka HTTP. Of course, it may not be brilliant as many of you want, but at least it solves the problem. You probably have your own thoughts on how validation should be implemented. I’d be really glad to read your comments regarding that.

Continue reading...