Last Updated : 28 Aug, 2024
Summarize
Comments
Improve
RESTful APIs have become the standard for building scalable and maintainable web services in web development. REST (Representational State Transfer) enables a stateless, client-server architecture where resources are accessed via standard HTTP methods. This article demonstrates how to create a RESTful API using Spring Boot and Spring MVC. We will walk through setting up the project, creating the necessary components, and testing the API endpoints.
RESTful API with Spring MVC
Spring Boot and Spring MVC simplify the development of RESTful APIs. Spring MVC follows the Model-View-Controller (MVC) pattern, separating concerns into distinct layers, making code easier to manage and extend. Spring Boot enhances this by automating configuration, allowing developers to focus on business logic rather than setup.
RESTful APIs, which follow the principles of Representational State Transfer (REST), use standard HTTP methods like GET, POST, PUT, and DELETE to interact with resources. By combining Spring Boot and Spring MVC, developers can quickly build scalable and maintainable web services with minimal configuration.
Key Features:
- Rapid Development: Spring Boot accelerates the development process with pre-configured setups and reduced boilerplate code.
- RESTful Endpoints: Spring MVC provides a robust framework for creating and managing RESTful web services.
- Layered Architecture: Clear separation of concerns with distinct layers for controller, service, and repository, improving maintainability.
- Database Integration: Seamless integration with databases like MySQL using Spring Data JPA for efficient data handling.
- Flexible Configuration: Customize application settings through
application.properties
orapplication.yml
files. - CRUD Operations: Supports full Create, Read, Update, and Delete operations, making it easy to manage resources.
- Exception Handling: Built-in support for handling errors and exceptions in a standardized way.
- Testing and Validation: Use Postman or similar tools to test and validate API endpoints.
- Security: Integrate with Spring Security for robust authentication and authorization mechanisms.
- Scalability: Designed to be easily scalable, supporting both small and large-scale applications.
Implementation of the RESTful API with Spring MVC
This example provides a foundational structure for building RESTful APIs using Spring Boot and Spring MVC. You can expand upon this by adding more entities, services, and controllers as needed.
Step 1: Create a New Spring Boot Project
Create a new Spring Boot project using IntelliJ IDEA. Choose the following options:
- Project Type: Maven
- Spring Boot Version: 3.3.2 (or latest stable version)
- Dependencies: Spring Web, Spring Data JPA, Spring Boot DevTools, MySQL Driver, Validation, Lombok

Step 2: Add Dependencies
Add the following dependencies into the Spring Boot project.

Project Structure
Once the project is created, the file structure should look like the following:

Step 3: Configure Application Properties
Open the application.properties
file and add the following MySQL and Hibernate configuration:
# Application namespring.application.name=spring-boot-restful-api# DataSource configuration for MySQLspring.datasource.url=jdbc:mysql://localhost:3306/mydb?useSSL=false&serverTimezone=UTCspring.datasource.username=rootspring.datasource.password=mypassword# Hibernate Dialect for MySQLspring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect# Hibernate DDL auto configurationspring.jpa.hibernate.ddl-auto=update# Show SQL queries in the consolespring.jpa.show-sql=true
Step 4: Create the User Entity Class
Create the User
entity class to represent the users
table in the database:
package com.gfg.springbootrestfulapi.model;import jakarta.persistence.*;import jakarta.validation.constraints.Email;import jakarta.validation.constraints.NotEmpty;import jakarta.validation.constraints.Size;import lombok.*;// Represents the 'users' table in the database@Entity@Table(name = "users")@Data@NoArgsConstructor@AllArgsConstructorpublic class User { // Primary key with auto-increment @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; // First name field with validation @NotEmpty(message = "First name is required") @Size(min = 2, message = "First name should have at least 2 characters") private String firstName; // Last name field with validation @NotEmpty(message = "Last name is required") @Size(min = 2, message = "Last name should have at least 2 characters") private String lastName; // Email field with validation and unique constraint @NotEmpty(message = "Email is required") @Email(message = "Email should be valid") @Column(unique = true) private String email;}
Step 5: Create the UserRepository Interface
Create the UserRepository
interface that extends JpaRepository
for CRUD operations:
package com.gfg.springbootrestfulapi.repository;import com.gfg.springbootrestfulapi.model.User;import org.springframework.data.jpa.repository.JpaRepository;import org.springframework.stereotype.Repository;// Repository interface for performing CRUD operations on User entity@Repositorypublic interface UserRepository extends JpaRepository<User, Long> { // Additional query methods can be defined here if needed}
This interface provides the methods like save(), findById(). findAll() and deletById() without the need to implement them.
Step 6: Create the Service Layer
Create the UserService
class to encapsulate the business logic:
package com.gfg.springbootrestfulapi.service;import com.gfg.springbootrestfulapi.exception.ResourceNotFoundException;import com.gfg.springbootrestfulapi.model.User;import com.gfg.springbootrestfulapi.repository.UserRepository;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import java.util.List;// Service class for business logic related to User entity@Servicepublic class UserService { @Autowired private UserRepository userRepository; // Create a new user public User createUser(User user) { return userRepository.save(user); } // Retrieve all users public List<User> getAllUsers() { return userRepository.findAll(); } // Retrieve user by ID public User getUserById(Long id) { return userRepository.findById(id) .orElseThrow(() -> new ResourceNotFoundException("User", "id", id)); } // Update user details public User updateUser(Long id, User userDetails) { User user = getUserById(id); user.setFirstName(userDetails.getFirstName()); user.setLastName(userDetails.getLastName()); user.setEmail(userDetails.getEmail()); return userRepository.save(user); } // Delete user by ID public void deleteUser(Long id) { User user = getUserById(id); userRepository.delete(user); }}
Step 7: Create the Controller Layer
Create the UserController
class to handle HTTP requests:
package com.gfg.springbootrestfulapi.controller;import com.gfg.springbootrestfulapi.model.User;import com.gfg.springbootrestfulapi.service.UserService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.http.HttpStatus;import org.springframework.http.ResponseEntity;import org.springframework.web.bind.annotation.*;import java.util.List;// REST Controller for handling user-related HTTP requests@RestController@RequestMapping("/api/users")public class UserController { @Autowired private UserService userService; // Create a new user @PostMapping public ResponseEntity<User> createUser(@RequestBody User user) { User createdUser = userService.createUser(user); return new ResponseEntity<>(createdUser, HttpStatus.CREATED); } // Retrieve all users @GetMapping public List<User> getAllUsers() { return userService.getAllUsers(); } // Retrieve user by ID @GetMapping("/{id}") public ResponseEntity<User> getUserById(@PathVariable Long id) { User user = userService.getUserById(id); return new ResponseEntity<>(user, HttpStatus.OK); } // Update user details @PutMapping("/{id}") public ResponseEntity<User> updateUser(@PathVariable Long id, @RequestBody User userDetails) { User updatedUser = userService.updateUser(id, userDetails); return new ResponseEntity<>(updatedUser, HttpStatus.OK); } // Delete user by ID @DeleteMapping("/{id}") public ResponseEntity<Void> deleteUser(@PathVariable Long id) { userService.deleteUser(id); return new ResponseEntity<>(HttpStatus.NO_CONTENT); }}
Step 8: Handle Exceptions
Create a custom exception class and a global exception handler:
ResourceNotFoundException.java:
package com.gfg.springbootrestfulapi.exception;public class ResourceNotFoundException extends RuntimeException { private String resourceName; private String fieldName; private Object fieldValue; public ResourceNotFoundException( String resourceName, String fieldName, Object fieldValue) { super(String.format("%s not found with %s : '%s'", resourceName, fieldName, fieldValue)); this.resourceName = resourceName; this.fieldName = fieldName; this.fieldValue = fieldValue; } // Getters (optional)}
GlobalExceptionHandler.java:
package com.gfg.springbootrestfulapi.exception;import org.springframework.http.HttpStatus;import org.springframework.http.ResponseEntity;import org.springframework.web.bind.annotation.ControllerAdvice;import org.springframework.web.bind.annotation.ExceptionHandler;import org.springframework.web.bind.annotation.ResponseBody;// Global exception handler for handling exceptions@ControllerAdvicepublic class GlobalExceptionHandler { @ExceptionHandler(ResourceNotFoundException.class) @ResponseBody public ResponseEntity<Object> handleResourceNotFoundException(ResourceNotFoundException ex) { return new ResponseEntity<>(ex.getMessage(), HttpStatus.NOT_FOUND); }}
Step 9: Main Application Class
No changes are required in the main class.
package com.gfg.springbootrestfulapi;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;// Main class to run the Spring Boot application@SpringBootApplicationpublic class SpringBootRestfulApiApplication { public static void main(String[] args) { SpringApplication.run(SpringBootRestfulApiApplication.class, args); }}
pom.xml file:
<?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>3.3.2</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.gfg</groupId> <artifactId>spring-boot-restful-api</artifactId> <version>0.0.1-SNAPSHOT</version> <name>spring-boot-restful-api</name> <description>spring-boot-restful-api</description> <url/> <licenses> <license/> </licenses> <developers> <developer/> </developers> <scm> <connection/> <developerConnection/> <tag/> <url/> </scm> <properties> <java.version>17</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-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-devtools</artifactId> <scope>runtime</scope> <optional>true</optional> </dependency> <dependency> <groupId>com.mysql</groupId> <artifactId>mysql-connector-j</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </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> <configuration> <excludes> <exclude> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </exclude> </excludes> </configuration> </plugin> </plugins> </build></project>
Step 10: Run the Application
After project is completed, run the application and it will start at port 8080.

Console Logs:

Step 11: Testing the API using Postman
We are using the Postman tool to test the API endpoints:
1. Create a User
POST http://localhost:8080/api/users
Output:

2. Retrieve all Users
GET http://localhost:8080/api/users
Output:

3. Get a User by ID
GET http://localhost:8080/api/users/1
Output:

4. Update a User by id
PUT http://localhost:8080/api/users/1
Output:

5. Delete a User by id
DELETE http://localhost:8080/api/users/1
Output:

By following these steps, we have created a simple RESTful API using Spring Boot and Spring MVC. This setup provides a solid foundation for building more complex APIs and integrating additional features as needed.
Next Article
Spring Boot - Custom Error Pages