Home > Software design >  Validate json values in response body before sending to spring controller to avoid response code 400
Validate json values in response body before sending to spring controller to avoid response code 400

Time:11-05

My Spring controller accepts application json response body as an object parameter. I don't see where I can intercept the json to validate the values before Spring controller receives it and complains when it doesn't cast.

Example: User sends json to endpoint - /createUser

Expecting: {"username":"johndoe", "pin": 1234} Receives: {"username": 1234, "pin": "johndoe"}

If string is sent for int or vice versa, server will show status 400. I'd like to validate the data myself and provide a custom json that details the values that are incorrectly set.

Thanks in advance!

CodePudding user response:

You could create your own class for the @RequestBody param in your controller and make a validation on them. You could use some supported annotations or create on your own. But don't forget to put the @Valid next to the @RequestBody, that's the key. E.g

@RestController
public class UserController {

    @PostMapping("/users")
    ResponseEntity<String> addUser(@Valid @RequestBody User user) {
        // persisting the user
        return ResponseEntity.ok("User is valid");
    }
    
    // standard constructors / other methods
    
}

For more information, you could find them here validation, create your own validator.

  • Related