How to Build a RESTful API with Spring Boot and Spring MVC?
Last Updated :
28 Aug, 2024
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
or application.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 name
spring.application.name=spring-boot-restful-api
# DataSource configuration for MySQL
spring.datasource.url=jdbc:mysql://localhost:3306/mydb?useSSL=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=mypassword
# Hibernate Dialect for MySQL
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect
# Hibernate DDL auto configuration
spring.jpa.hibernate.ddl-auto=update
# Show SQL queries in the console
spring.jpa.show-sql=true
Step 4: Create the User Entity Class
Create the User
entity class to represent the users
table in the database:
Java
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
@AllArgsConstructor
public 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:
Java
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
@Repository
public 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:
Java
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
@Service
public 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:
Java
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:
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:
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
@ControllerAdvice
public 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.
Java
package com.gfg.springbootrestfulapi;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
// Main class to run the Spring Boot application
@SpringBootApplication
public class SpringBootRestfulApiApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootRestfulApiApplication.class, args);
}
}
pom.xml file:
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>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.
Similar Reads
Securing Spring Boot API With API Key and Secret
In Web applications, securing the APIs is critical. One of the common methods of securing the APIs is by using API keys and secrets. This ensures that only the authorized clients can access the API endpoints. This article can guide you through the process of securing the Spring Boot API using the AP
6 min read
Spring Boot â Building REST APIs with HATEOAS
In this article, we will explore how to build RESTful APIs using the Spring Boot with HATEOAS (Hypermedia as the Engine of Application State). HATEOAS is the key component of the REST application architecture, where each resource not only provides the data but also includes links to other actions th
5 min read
Properties with Spring and Spring Boot
Java-based applications using the Spring framework and its evolution into the Spring Boot and the properties play a crucial role in configuring the various aspects of the application. Properties can allow the developers to externalize the configuration settings from the code. Understanding how to wo
4 min read
How to Extract TV Show Details via REST API and Spring MVC?
REpresentational State Transfer (REST) is an architectural style that defines a set of constraints to be used for creating web services. REST API is a way of accessing web services in a simple and flexible way without having any processing. Spring MVC is a Web MVC Framework for building web applicat
9 min read
How to Create a REST API using Java Spring Boot?
Representational State Transfer (REST) is a software architectural style that defines a set of constraints for creating web services. RESTful web services allow systems to access and manipulate web resources through a uniform and predefined set of stateless operations. Unlike SOAP, which exposes its
4 min read
Spring Boot - How to set a Request Timeout for a REST API
In Microservice architecture, there are multiple microservices available for an application. For the application to work properly necessary services need to communicate with each other. There can be communication of messaging type or REST calls. How does REST API Work?In REST Calls the process is sy
6 min read
Spring Boot â Using Spring Boot with Apache Camel
Apache Camel and Spring Boot are two powerful frameworks that can be seamlessly integrated to build robust, scalable, and efficient applications. Apache Camel is an open-source integration framework that provides an extensive range of components and connectors, enabling developers to integrate diffe
5 min read
How to Create and Setup Spring Boot Project in Spring Tool Suite?
Spring Boot is built on the top of the spring and contains all the features of spring. And is becoming a favorite of developers these days because of its rapid production-ready environment which enables the developers to directly focus on the logic instead of struggling with the configuration and se
3 min read
Add Build Properties to a Spring Boot Application
Spring Boot framework is an open-source framework for developing web applications with high performance and the Spring Boot makes it much easier to develop Spring-based applications developed by Java programming In this article, we will learn how to add build properties to a Spring Boot Application.
4 min read
Returning an Image or a File with Spring
In web development, it is common for servers to send various types of content to clients, including static and dynamic data, images, and files. The Spring Framework provides powerful tools to handle these requirements efficiently, allowing developers to return images and files directly from endpoint
3 min read