Restful API Develpoment in Spring Boot
REST (Representational State Transfer) is a widely used architectural style for building APIs. It leverages HTTP methods to perform operations on resources. In Spring Boot, building RESTful services is facilitated by annotations like @RestController
, @RequestMapping
, and the usage of HTTP methods like GET
, POST
, PUT
, and DELETE
. In this article, we will explore how to build RESTful APIs using these tools.
Introduction to REST#
REST is a stateless architecture, where each request from the client to the server must contain all the information needed to understand and process the request. RESTful APIs follow the following key principles:
- Statelessness: Each request is independent, and the server doesn't retain client state.
- Uniform Interface: APIs use standard HTTP methods like GET, POST, PUT, and DELETE.
- Client-Server Separation: The client and server are independent and can evolve separately.
1. Visit https://start.spring.io/ and generate the employee service project and open in Intellij#
We wil be building simple employee service with basic crud operations.

2. Crete the following folders and files under your packageĀ #

3. Configuring Postgres Database#
4. Adding model mapper configuration and dependency in pom.xml#
Add the following model mapper bean in AppConfig file, we will use model mapper to convert dto to entity and vise versa.
5. Create Employee Entity class#
6. Data Transfer Objects (DTOs)#
DTOs are used to transfer data between the client and server. They contain only the necessary fields required for data exchange.
7. Creating Employee repository interface#
@Repository
: This annotation is a specialization of the@Component
annotation in Spring. It marks the class as a Data Access Object (DAO), which means itās responsible for handling the data persistence logic in the application. In this case, itās the repository for theEmployee
entity.- The
EmployeeRepository
extendsJpaRepository
, which is a Spring Data JPA interface that provides standard CRUD operations like saving, updating, deleting, and finding entities. By extendingJpaRepository
, we avoid manually implementing these basic database operations. JpaRepository<Employee, Long>
defines that this repository is for theEmployee
entity class, andLong
is the type of the primary key (id
).- List<Employee> findByEmail(String email); This is a custom query method provided by Spring Data JPA. Without writing SQL, you can define custom queries by following a naming convention.
8. RESTful Services with Spring Boot, building employee controller#
Spring Boot simplifies the development of RESTful services with annotations like @RestController
and @RequestMapping
. Let's dive into an example:
In this example:
@RestController
marks the class as a REST controller, meaning it will handle HTTP requests and return JSON responses.@RequestMapping("/employees")
defines the base path for all the endpoints in this controller.@RequiredArgsConstructor
is a Lombok annotation to automatically generate a constructor forfinal
fields.
9. Controller Implementation#
GET Method: Retrieving Data#
The @GetMapping
annotation is used for retrieving data. It fetches an employee by their ID:
@PathVariable
maps the{id}
in the URL to the method parameter.ResponseEntity.ok()
returns an HTTP 200 response with the employee's data.
POST Method: Creating New Data#
The @PostMapping
is used to create a new employee:
@RequestBody
binds the incoming JSON request body to theEmployeeDto
.- The response is created with the
CREATED
status (HTTP 201).
PUT Method: Updating Existing Data#
@PutMapping
is used to update an existing employee:
This method updates an employee's details and returns the updated employee object with an HTTP 200 status.
DELETE Method: Removing Data#
@DeleteMapping
is used for deleting an employee:
This method deletes an employee and returns an HTTP 204 (No Content) response if successful.
10. Service Layer#
The service layer contains business logic and interacts with the repository layer.
ModelMapper
is used to mapEmployeeDto
toEmployee
and vice versa.- This layer abstracts the business logic from the controller, making the code cleaner and more modular.
11. Crete new Resource not found exception class#
12. Exception Handling with @RestControllerAdvice
#
Handling exceptions in RESTful APIs is important for returning meaningful error messages. The @RestControllerAdvice
annotation handles exceptions globally.
This advice handles ResourceNotFoundException
and RuntimeException
, ensuring that the client receives proper error responses.
12. Now Open post man to test our apis#
1. Create Employee#
Run your application, after running you can see in console the hibernate DDL queries to create the employee table.

Now go to post man and hit the create employee endpoint

2. Get Employee by id#

3. Update Employee by id#

4. Delete Employee by id#

In this article, we covered the essential steps for building a RESTful API in Spring Boot, including setting up a basic project, configuring a database, creating entity classes, and implementing CRUD operations through controllers and services. We also explored exception handling to make APIs more robust and user-friendly. By leveraging Spring Bootās powerful features and annotations, you can rapidly develop scalable and maintainable RESTful services.