Validation For Rest API

 For Validation need to add dependancy in Pom xml file 

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-validation</artifactId>

</dependency>


also Added jakarta.validation.constraints on User Pojo Class


@Size(min = 2)

private String name;

@Past

private LocalDate birthDate;

@Pattern(regexp = "^[a-zA-Z0-9+_.-]+@[a-zA-Z0-9.-]+$")

private String emailID;


Also Add @Valid Annothation in Post request of Resrouse Creation

@PostMapping("/users")

public ResponseEntity<User> addUser(@Valid @RequestBody User user) {

User savedUser = userDaoService.save(user);

URI location = ServletUriComponentsBuilder.fromCurrentRequest()

.path("/{id}")

.buildAndExpand(savedUser.getId())

.toUri();

return ResponseEntity.created(location).build();

}

For less than 2 size Name OR Future Date OR wrong mail pattern will give you

same error which is 400 Bad Request Only







To Resolve the Generic Exception as Bad Request to Proper Exception

to handle by giving proper Response to Consumer of this Service by Adding

your Exception into the your @ControlerAdvice Exception Class

where you can handle the all the exception


Given below Customized ResponseEntityExceptionHandler class

extends ResponseEntityExceptionHandler which handle diffrernt not valid argument exceptions

handleMethodArgumentNotValid this method override from ResponseEntityExceptionHandler

also we have created ErrorDetails Class which will set the Response as PoJo

and return if this exception occured


@ControllerAdvice

public class CustomizedResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {


@Override

protected ResponseEntity<Object> handleMethodArgumentNotValid(

MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatusCode status, WebRequest request) {

ErrorDetails errorDetails = new ErrorDetails(LocalDateTime.now(),

ex.getMessage(), request.getDescription(false), "Bad Request");

return new ResponseEntity<Object>(errorDetails, HttpStatus.BAD_REQUEST);

}

}


public class ErrorDetails {

private LocalDateTime timestamp;

private String message;

private String details;

private String errorGenerator;

//constructor and getter/setter

}


now with Post Body

Post Request body




Get Response as

{
"timestamp": "2023-07-03T03:52:01.8045701",
"message": "Validation failed for argument [0] in public org.springframework.http.ResponseEntity<com.khan.rest.webservices. FirstRestFulWebServices.user.User> com.khan.rest.webservices. FirstRestFulWebServices.user.UserResourceController.addUser (com.khan.rest.webservices.FirstRestFulWebServices.user.User) with 3 errors: [Field error in object 'user' on field 'emailID': rejected value [khan.com]; codes [Pattern.user.emailID,Pattern.emailID,Pattern.java.lang.String,Pattern]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [user.emailID,emailID]; arguments []; default message [emailID],[Ljakarta.validation.constraints.Pattern$Flag; @dc3561,^[a-zA-Z0-9+_.-]+@[a-zA-Z0-9.-]+$]; default message [must match \"^[a-zA-Z0-9+_.-]+@[a-zA-Z0-9.-]+$\"]] [Field error in object 'user' on field 'birthDate': rejected value [4000-07-02]; codes [Past.user.birthDate,Past.birthDate,Past.java.time.LocalDate,Past]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [user.birthDate,birthDate]; arguments []; default message [birthDate]]; default message [must be a past date]] [Field error in object 'user' on field 'name': rejected value []; codes [Size.user.name,Size.name, Size.java.lang.String,Size]; arguments [org.springframework.context.support. DefaultMessageSourceResolvable: codes [user.name,name]; arguments []; default message [name],2147483647,2]; default message [size must be between 2 and 2147483647]] ",
"details": "uri=/users",
"errorGenerator": "Bad Request"
} we have recieved message with 3 error because all three value were wrong as per validation we can customize the error message as well as per the customer Consumer requirment { "timestamp": "2023-07-04T11:11:22.7724612", "message": "Validation failed for argument [0] in public org.springframework.http.ResponseEntity<com.khan.rest.webservices.FirstRestFulWebServices.user.User> com.khan.rest.webservices.FirstRestFulWebServices.user.UserResourceController.addUser(com.khan.rest.webservices.FirstRestFulWebServices.user.User) with 3 errors: [Field error in object 'user' on field 'name': rejected value []; codes [Size.user.name,Size.name,Size.java.lang.String,Size]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [user.name,name]; arguments []; default message [name],2147483647,2]; default message [Name min size is 2 atleast]] [Field error in object 'user' on field 'birthDate': rejected value [4000-07-02]; codes [Past.user.birthDate,Past.birthDate,Past.java.time.LocalDate,Past]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [user.birthDate,birthDate]; arguments []; default message [birthDate]]; default message [birthDate should be lessthan from todays date]] [Field error in object 'user' on field 'emailID': rejected value [khan.com]; codes [Pattern.user.emailID,Pattern.emailID,Pattern.java.lang.String,Pattern]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [user.emailID,emailID]; arguments []; default message [emailID], [Ljakarta.validation.constraints.Pattern$Flag;@dc3561,^[a-zA-Z0-9+_.-]+@[a-zA-Z0-9.-]+$]; default message [email in not in proepr format]] ", "details": "uri=/users", "errorGenerator": "Bad Request" } by adding message = attribute into your validation annotations

private Integer id;

@Size(min = 2, message = "Name min size is 2 atleast")

private String name;

@Past(message = "birthDate should be lessthan from todays date")

private LocalDate birthDate;

@Pattern(regexp = "^[a-zA-Z0-9+_.-]+@[a-zA-Z0-9.-]+$", message = "email in not in proepr format")

private String emailID;

But as you can see given avobe error are all list of 3 exceptions with clumsy formate which sometime hard to understand so we can more customize and only send back to 1 first exception so that we can handle it first that than other one by by we can handle as we get those exception once the first one is fixed by adding ex.getFieldError().getDefaultMessage() ==> will give you first exception

@Override

protected ResponseEntity<Object> handleMethodArgumentNotValid(

MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatusCode status, WebRequest request) {

ErrorDetails errorDetails = new ErrorDetails(LocalDateTime.now(),

ex.getFieldError().getDefaultMessage(), request.getDescription(false), "Bad Request");

return new ResponseEntity<Object>(errorDetails, HttpStatus.BAD_REQUEST);

}

First Atempt to Post : we are getting Email is not in proper formate so we will fix that


In Second Attept post now getting Birth date is Future Date


Now on Thired Attempt after fix birthdate from 4000 year future date to 2000 past date now Post getting name can not be less than 2 charecters



Now After Fix Name,Birthdate,Email: we are getting 201 created success

Comments

Popular posts from this blog

Introduction of RESTful Web Service

Learn JPA and Hibernate

Implementing Dynamic Filtering for Rest API