Table of contents
1.
Introduction📜
2.
Implementing Validations 🔐
3.
Frequently Asked Questions
3.1.
What does Spring Boot's post function do?
3.2.
What is Spring-HATEOAS?
3.3.
What does spring boot's @RestController annotation mean?
3.4.
Can @component take the place of @controller?
3.5.
Can we build a resource using Put rather than POST?
4.
Conclusion
Last Updated: Mar 27, 2024
Medium

Implementing Validations for RESTful Services

Author Rajat Agrawal
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction📜

Spring Boot is a project that uses the Spring Framework as its foundation. It makes setting up, configuring, and running simple web-based applications easier and faster. 
Spring Boot is the foundation of every developer's experience, regardless of what they're building. Spring Boot helps us to do it as quickly as possible with the least amount of configuration required upfront. 

Spring Boot

In this blog, we will learn how to Implement Validations for RESTful Services in spring boot.

Implementing Validations 🔐

Validation is a prerequisite for all services. We will go through the Java Validation API and how to use it to add validation to our beans file. When we receive a request to create a user, we must validate its content. If it is invalid, we need to respond appropriately.
Let's see how to validate a request in the spring project.
You need to follow some steps to implement validation in the spring project.

Step 1: Open the UserResources.java file.

Step 2: Add @Valid annotation. It is a Javax validation API. The default classpath of this annotation is spring-boot-starter-web.

UserResources.java 
 

package com.codingninjas.server.main.user;  
import java.net.URI;  
import java.util.List;  
import javax.validation.Valid;  
import org.springframework.web.bind.annotation.DeleteMapping;  
import org.springframework.web.bind.annotation.GetMapping; 
import org.springframework.beans.factory.annotation.Autowired;  
import org.springframework.http.ResponseEntity;  
import org.springframework.web.bind.annotation.RequestBody;  
import org.springframework.web.bind.annotation.RestController; 
import org.springframework.web.bind.annotation.PathVariable;  
import org.springframework.web.bind.annotation.PostMapping;  
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;  
@RestController  
public class UserResources   
{  
@Autowired  
private UserDaoService service;  
@GetMapping("/users")  
public List<User> getAllUsers()  
{  
return service.findAll();  
}  
//Get a particular user detail  
@GetMapping("/users/{id}")  
public User getUser(@PathVariable int id)  
{  
User user= service.findOne(id);  
if(user==null)  
//Throws Runtime Exception  
throw new UserNotFoundException("id: "+ id);  
return user;  
}  

//Method to delete a user resource  
@DeleteMapping("/users/{id}")  
public void deleteUser(@PathVariable int id)  
{  
User user= service.deleteById(id);  
if(user==null)  

//Throws Runtime Exception 
throw new UserNotFoundException("id: "+ id);  
}  

@PostMapping("/users")  
public ResponseEntity<Object> createUser(@Valid @RequestBody User user)     
{  
User sevedUser=service.save(user);    
URI location=ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}").buildAndExpand(sevedUser.getId()).toUri();  
return ResponseEntity.created(location).build();  
}  
}  
You can also try this code with Online Java Compiler
Run Code


Step 3: Open Users.java file.

Step 4: Add @Size(min = 5)  annotation just above the name variable. This will make sure that the name length should not less than 5.

Users.java
 

package com.codingninjas.server.main.user;  
import java.util.Date;  
import javax.validation.constraints.Size;  
import javax.validation.constraints.Past;  

public class User   
{  
private Integer id;  

@Size(min=5)  
private String name;   
private String city;  

//Default constructor     
protected User()  
{  
      
} 
 
public User(Integer id, String name, String city)   
{  
super();  
this.id = id;  
this.name = name;  
this.dob = dob;  
}  
public Integer getId()   
{  
return id;  
}  
public void setId(Integer id)   
{  
this.id = id;  
}  
public String getName()   
{  
return name;  
}  
public void setName(String name)   
{  
this.name = name;  
}  
public String getCity()   
{  
return city;  
}  
public void setCity(String city)   
{  
this.city = city;  
}  
@Override  
public String toString()   
{   
return String.format("User [id=%s, name=%s, city=%s]", id, name, city);  
}  
}  
You can also try this code with Online Java Compiler
Run Code


Step 5: Open RestClient in VS Code, select Send Request and send the POST request to the URL: localhost:3000/users.
It will return Status: 201 Created

Request

Send another POST request. But this time the name should have less than five characters.
It will return the Status: 400 Bad Request.

Request

Frequently Asked Questions

What does Spring Boot's post function do?

The Spring Boot applications that handle client post requests with JSON data in the header typically utilize the PostMapping() annotation. Launching the project's Spring web.

What is Spring-HATEOAS?

Spring-HATEOAS is an API library. These APIs can be used in combination with Spring MVC to build REST representations that comply with the HATEOAS principle.

What does spring boot's @RestController annotation mean?

The @Controller and @ResponseBody annotations are already present in the Spring RestController annotation, which is a convenience annotation. Applying this annotation to a class designates it as a request handler. The Spring MVC annotation, Spring RestController, is used to build RESTful web services.

Can @component take the place of @controller?

There is no difference between @Component@Service@Controller, and @Repository. The generic annotation @Component is used to represent the component of our MVC.

Can we build a resource using Put rather than POST?

You can build or edit a resource using either POST or PUT, as both can be used to submit data. Because PUT is idempotent, it is preferred by many web developers for creating a resource on the server. No matter how often you call PUT, the resource's condition won't be in danger.

Conclusion

In this article, we have extensively discussed how to Implement Validations for RESTful Services in spring boot. I hope you enjoyed reading this article on Implementing Validations for RESTful Services. 

If you want to learn more, check out our articles on Implementing DELETE Method to Delete a User ResourceImplementing HATEOAS for RESTful ServicesTechnological Services in Ready APIWhat Is Web2Py?Why To Use Web2py?Postbacks and Internationalization in web2pyThird Party Modules In Web2pyTasks In Web2py, and  XML in Web2py.

Happy Coding!

Live masterclass