Response Entity in Rest API CRUD Example Spring Boot

In this topic, we will learn what is ResponseEntity, and how to use Response Entity in Rest API crud example in the Spring Boot Application. We will create an example of Rest API CRUD operation in the Spring Boot application step-by-step. We are creating a Spring Boot Project using Spring Web, Spring Data JPA and MySQL Driver to implement CRUD rest API with ResponseEntity.

response_entity_in_rest_api_crud_example

Table of contents

  1. What is ResponseEntity?
  2. About the Response Entity in Rest API CRUD Example
  3. Creating a Rest API CRUD Example
  4. 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 Response Entity in 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 give output as JSON and HTTP code by using ResponseEntity.

3. Creating a Rest API CRUD Example

These are the following steps to develop this example:

     1. Creating a Spring Boot Starter Project
     2. Keep Eclipse IDE ready
     3. Defining Configuration
     4. Creating a JPA Entity
     5. Creating a JPA Repository
     6. Creating a Service
     7. Creating a Controller
     8. Run the Project

1. Creating a Spring Boot Starter Project

We are creating a Spring Project from the web tool Spring Initializr. You can Spring Project from the IDE which you are using.
Add the following dependencies:
   • Spring Web
   • Spring Data JPA
   • Mysql Driver

 2. Keep Eclipse IDE ready

We are using Eclipse IDE to import the created Spring Boot project. You can import other IDE which you are comfortable to use. You can refer to this article to create and set up the Spring Boot Project in Eclipse IDE to import the Project of Spring Boot.

Project Structure
response_entity_rest_api_spring_boot
Maven Dependency

Here is the complete pom.xml file of this project.
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. Defining Configuration

We are configuring MySQL database configuration in the application.properties file.
application.properties

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. Creating a JPA Entity

We are creating a User JPA entity class which has properties(id, userName, mobileNo, emailId, city and password). This class is annotated with @Entity to create a table in the database using Java code.

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. Creating a JPA Repository

We creating a UserRepository interface extending JpaRepository to inherit all methods of the JpaRepository.
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. Creating a Service

We are creating a UserService interface which has been declaring four methods.
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);
}

We are creating an implementation class of the UserService interface and defining methods of it.
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);
	}
}

→ This class is annotated with @Service annotation to make it a service class.

7. Creating a Controller

We are creating a UserController class annotated with @RestController annotation to make it RestController to handle request mappings.
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);
		}
	}
}

→  JSON and HttpStatus codes as a response for consumers of this Rest API with the help of ResponseEntity.
→ The 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
Test API in the Postman tool:
POST: http://localhost:8080/api/save

response_entity_rest_api_spring_boot

GET: http://localhost:8080/api/users

response_entity_rest_api_spring_boot

GET: http://localhost:8080/api/user/4

response_entity_rest_api_spring_boot

PUT: http://localhost:8080/api/update/4

response_entity_rest_api_spring_boot

DELETE: http://localhost:8080/api/delete/4

response_entity_rest_api_spring_boot

4. Conclusion

In this example, we learnt about ResponseEntity and how to implement it in Spring Boot restful web services.

Leave a Comment