How to Validate Request Body in Spring Boot


The spring boot rest supports for restful web services. The restful web service contains headers and body. The header contains the information about the body. The body contains the actual data. The data can be in any format. The restful web service normally transfers the data in JSON format.

The spring boot controller helps to convert the json data to java object and validates the data. Spring boot validates before executing the method in the controller. In this post, we will see, how to read request body in spring boot and how to validate request body in spring boot controller. The step by step procedure is added to validate the request body.



Step 1 – Add dependency in pom.xml

The “spring-boot-starter-validation” dependency will include all the jars needed for the validation of the request body. The web application needs the dependence of “spring-boot-starter-browser.” This will allow the tomcat server and start as a web application. The default “spring-boot-starter-test” test dependency will be applied to pom.xml for the unit testing.

If you have created a spring boot application, now you’re trying to incorporate the validation code, then add the “spring-boot-starter-validation” dependency to the pom.xml file. The complete pom.xml file will be as shown below.

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.2.5.RELEASE</version>
		<relativePath /> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.yawintutor</groupId>
	<artifactId>Spring-Application</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>SpringBootValidation</name>
	<description>Spring Boot Project</description>

	<properties>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-validation</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>


Step 2 – Add @RequestBody annotation

The request body contains the actual data in json format. The annotation @RequestBody is used to handle the request body. This annotation converts the json string to the java object. It parses the json string and creates the java bean object and assigns the corresponding value in the object.

In this post, the json is converted to student object. Student object contains a variable “age”. Spring boot creates Student object and assigns value to the variable.

The example is shown in the next step along with validation tags.



Step 3 – Add @Valid annotation for validation

The @Valid annotation is used to specify the rest controller to be validated. The spring boot application validates the method before it is called.

Student.java

package com.yawintutor;

import javax.validation.constraints.Min;

public class Student {

	@Min(5)
	private int age;

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

}

TestController.java

package com.yawintutor;

import javax.validation.Valid;

import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
@Validated
public class TestController {

	@PostMapping("/student/")
	ResponseEntity<String> student(@Valid @RequestBody Student student) {
		return ResponseEntity.ok("Your age is " + student.getAge());
	}
}


Step 4 – Run the application

To validate the request body, start the application on the spring boot. Call the curl command or import and run in postman tool. 

curl -X POST \
  http://localhost:8080/student/ \
  -H 'Cache-Control: no-cache' \
  -H 'Content-Type: application/json' \
  -H 'Postman-Token: 6f258a7f-d361-44f8-9c9b-b5bdc2828250' \
  -d '{"age":"5"}'

Output

Your age is 5

If the invalid json value is passed as part of url the validation will fail. The url below displays the curl command with invalid data.

curl -X POST \
  http://localhost:8080/student/ \
  -H 'Cache-Control: no-cache' \
  -H 'Content-Type: application/json' \
  -H 'Postman-Token: 6f258a7f-d361-44f8-9c9b-b5bdc2828250' \
  -d '{"age":"3"}'

Output

{
    "timestamp": "2020-03-26T16:42:04.107+0000",
    "status": 400,
    "error": "Bad Request",
    "errors": [
        {
            "codes": [
                "Min.student.age",
                "Min.age",
                "Min.int",
                "Min"
            ],
            "arguments": [
                {
                    "codes": [
                        "student.age",
                        "age"
                    ],
                    "arguments": null,
                    "defaultMessage": "age",
                    "code": "age"
                },
                5
            ],
            "defaultMessage": "must be greater than or equal to 5",
            "objectName": "student",
            "field": "age",
            "rejectedValue": 3,
            "bindingFailure": false,
            "code": "Min"
        }
    ],
    "message": "Validation failed for object='student'. Error count: 1",
    "path": "/student/"
}



Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *