Response Entity in Rest API CRUD Example Spring Boot
We will learn what is ResponseEntity, and how to use ResponseEntity in Rest API in the Spring Boot Application. We will create step-by-step an example of Rest API CRUD operation in the Spring Boot application.
Table of content:
- What is ResponseEntity?
- About the Rest API CRUD Example
- Create a Rest API CRUD Example using ResponseEntity in Spring Boot
- Conclusion
1. What is ResponseEntity?
ResponseEntity is indicated to represent the entire HTTP response. We can manage anything that goes into it: status code, headers, and body. While @ResponseBody is used for the HTTP response body and @ResponseStatus annotates the status code of the HTTP response.
2. About the Rest API CRUD Example
In this example of the application, we will perform CRUD operations (Insert, Select, Update and Delete). We will JPA entity class for table creation into the database. We will create one interface that extends the JpaRepository interface for persistence operation performed on the database. We will create one service interface and one service class that implements the service interface.This service class auto wiring that interface extends JpaRepository for using predefined methods. We will create one controller class which is the auto-wiring service interface for persistence logic methods. This controller class contains request handler methods which are giving output as JSON and HTTP code by using ResponseEntity.
3. Create a Rest API CRUD Example using ResponseEntity in Spring Boot
These are the following steps to develop this example:
- Keep eclipse IDE ready(STS Integrated)
- Create a Spring Boot Starter Project
- Define Database Connection in the application.properties file
- Create Entity class
- Create DAO
- Create a Service
- Create a Rest Controller class
- Run the Project
1. Keep eclipse IDE ready(STS Integrated)
Refer to this article How to Create Spring Project in IDE to create Spring Boot Project in Eclipse IDE.
2. Create a Spring Boot Starter Project
Add the following dependencies:
- Spring Web
- Spring Data JPA
- Mysql Driver
Maven Dependency
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.6.2</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.poc.rest</groupId>
<artifactId>rest</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>Spring_Boot_Rest_Api_With_Response_Entity</name>
<description>Demo project for Spring Boot Rest API with ResponseEntity</description>
<properties>
<java.version>8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</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>
3. Define Database Connection in the application.properties file
spring.datasource.url=jdbc:mysql://localhost:3306/user_db?useSSL=false
spring.datasource.username=root
spring.datasource.password=root
spring.jpa.hibernate.ddl-auto=update
spring.jpa.generate-ddl=true
spring.jpa.show-sql=true
→ There is no need to define below Driver Class Name. This is implicitly registered.
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
4. Create Entity class
User.java:
package com.poc.rest.entity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String userName;
private String mobileNo;
private String emailId;
private String city;
private String password;
public User() {
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getMobileNo() {
return mobileNo;
}
public void setMobileNo(String mobileNo) {
this.mobileNo = mobileNo;
}
public String getEmailId() {
return emailId;
}
public void setEmailId(String emailId) {
this.emailId = emailId;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
→ This User class is a JavaBean class because it applies the rules of the JavaBean class.
5. Create DAO
UserRespository.java:
package com.poc.rest.dao;
import org.springframework.data.jpa.repository.JpaRepository;
import com.poc.rest.entity.User;
public interface UserRespository extends JpaRepository<User, Integer> {
}
→ JpaRepository is a predefined interface from Spring Data JPA. It is persistence methods like save( ), delete( ), findAll( ) etc.
6. Create a Service
UserService.java:
package com.poc.rest.service;
import java.util.List;
import com.poc.rest.entity.User;
public interface UserService {
public List<User> getUser();
public void save(User user);
public User findById(Integer id);
public void delete(User user);
}
UserServiceImpl.java:
package com.poc.rest.service;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.poc.rest.dao.UserRespository;
import com.poc.rest.entity.User;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserRespository userRepo;
@Override
public List<User> getUser() {
return userRepo.findAll();
}
@Override
public void save(User user) {
userRepo.save(user);
}
@Override
public User findById(Integer id) {
return userRepo.findById(id).get();
}
@Override
public void delete(User user) {
userRepo.delete(user);
}
}
7. Create a Rest Controller class
UserController.java:
package com.poc.rest.controller;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.poc.rest.entity.User;
import com.poc.rest.service.UserService;
@RestController
@RequestMapping("/api")
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/users")
public ResponseEntity<?> getUser() {
Map<String, Object> map = new LinkedHashMap<String, Object>();
List<User> userList = userService.getUser();
if (!userList.isEmpty()) {
map.put("status", 1);
map.put("data", userList);
return new ResponseEntity<>(map, HttpStatus.OK);
} else {
map.clear();
map.put("status", 0);
map.put("message", "Data is not found");
return new ResponseEntity<>(map, HttpStatus.NOT_FOUND);
}
}
@PostMapping("/save")
public ResponseEntity<?> saveUser(@RequestBody User user) {
Map<String, Object> map = new LinkedHashMap<String, Object>();
userService.save(user);
map.put("status", 1);
map.put("message", "Record is Saved Successfully!");
return new ResponseEntity<>(map, HttpStatus.CREATED);
}
@GetMapping("/user/{id}")
public ResponseEntity<?> getUserById(@PathVariable Integer id) {
Map<String, Object> map = new LinkedHashMap<String, Object>();
try {
User user = userService.findById(id);
map.put("status", 1);
map.put("data", user);
return new ResponseEntity<>(map, HttpStatus.OK);
} catch (Exception ex) {
map.clear();
map.put("status", 0);
map.put("message", "Data is not found");
return new ResponseEntity<>(map, HttpStatus.NOT_FOUND);
}
}
@DeleteMapping("/delete/{id}")
public ResponseEntity<?> deleteUser(@PathVariable Integer id) {
Map<String, Object> map = new LinkedHashMap<String, Object>();
try {
User user = userService.findById(id);
userService.delete(user);
map.put("status", 1);
map.put("message", "Record is deleted successfully!");
return new ResponseEntity<>(map, HttpStatus.OK);
} catch (Exception ex) {
map.clear();
map.put("status", 0);
map.put("message", "Data is not found");
return new ResponseEntity<>(map, HttpStatus.NOT_FOUND);
}
}
@PutMapping("/update/{id}")
public ResponseEntity<?> updateUserById(@PathVariable Integer id, @RequestBody User userDetail) {
Map<String, Object> map = new LinkedHashMap<String, Object>();
try {
User user = userService.findById(id);
user.setUserName(userDetail.getUserName());
user.setMobileNo(userDetail.getMobileNo());
user.setEmailId(userDetail.getEmailId());
user.setCity(userDetail.getCity());
user.setPassword(userDetail.getPassword());
userService.save(user);
map.put("status", 1);
map.put("data", userService.findById(id));
return new ResponseEntity<>(map, HttpStatus.OK);
} catch (Exception ex) {
map.clear();
map.put("status", 0);
map.put("message", "Data is not found");
return new ResponseEntity<>(map, HttpStatus.NOT_FOUND);
}
}
}
→ We are giving JSON and HttpStatus codes as a response for consumers of this Rest API with the help of ResponseEntity.
→ ResposeEntity class is very important for developers when we are developing a rest API in the spring boot.
8. Run the Project
Right-click on the project’s SpringBootApplication class then click on Run as Java Application.
You can test API through the Postman tool:
Post Type: http://localhost:8080/api/save
Get Type: http://localhost:8080/api/users
Get Type: http://localhost:8080/api/user/4
Put Type: http://localhost:8080/api/update/4
Delete Type: http://localhost:8080/api/delete/4
4. Conclusion
In this example, we learnt about ResponseEntity and how to implement in this example.
Leave your thought here
Your email address will not be published. Required fields are marked *