Building A CRUD RESTful API - Web Service With Spring Boot - by Gabriel Pulga - The Startup - Medium
Building A CRUD RESTful API - Web Service With Spring Boot - by Gabriel Pulga - The Startup - Medium
Building A CRUD RESTful API - Web Service With Spring Boot - by Gabriel Pulga - The Startup - Medium
Get unlimited access to the best of Medium for less than $1/week. Become a member
Overview
This guide aims to help you create from scratch a CRUD RESTful API with Spring Boot. We’ll create an User entity and develop its
endpoints accordingly with a Rest Controller and a Service class.
To learn more about HTTP methods click here , and RESTful APIs, click here.
Later on we’ll be using this project as a base and evolve it, adding new functionalities.
Building our User class with its own repository and particular attributes.
Creating CRUD (Create, Read, Update, Delete) endpoints for our User class with a respective Controller and Service.
Differences between GET, POST, PUT and DELETE from HTTP request methods.
Meaning of all annotations used to make the code cleaner, easier to read and easier to maintain.
https://medium.com/swlh/building-a-crud-restful-api-web-service-with-spring-boot-a4f29edfbcd3 1/16
14/04/2024, 22:05 Building a CRUD RESTful API/Web Service with Spring Boot | by Gabriel Pulga | The Startup | Medium
JDK 1.8+
Getting started
We’ll first need to bootstrap our project with Spring Initializr.
This can be done by going to http://start.spring.io/ or if you’re using IntelliJ, by creating a New Project and choosing Spring
Initializr instead of the standard Java option in the quick menu.
Lombok : Java library that makes the code cleaner and gets rid of boilerplate code.
Spring WEB : Product of the Spring community focused on creating document-driven Web services.
Rest Repositories HAL Browser : Provides an in-browser GUI to traverse our REST API.
Spring Data JPA : Provides repository support for the Java Persistence API (JPA).
This step can also be done by writing the dependencies in the pom.xml file present in our project folder :
<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>org.springframework.data</groupId>
<artifactId>spring-data-rest-hal-browser</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</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>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
https://medium.com/swlh/building-a-crud-restful-api-web-service-with-spring-boot-a4f29edfbcd3 2/16
14/04/2024, 22:05 Building a CRUD RESTful API/Web Service with Spring Boot | by Gabriel Pulga | The Startup | Medium
</exclusions>
</dependency>
</dependencies>
src/main/java/com/usersapi/domain/user/User.java
@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity
One thing that may come up to you as unclear, is why are we implementing serialization in our User class?
It’s due to the fact that serialization converts an object into a sequence of bytes which can then be saved to a database or
transferred over a network. When working with our User entity, this may come in handy later on.
When working with JPA as our persistence layer, it’s necessary to map our API to persist our objects of choice.
@Entity : Tells that our class can be represented by a table in the database, with each instance representing a row.
@Id : Specifies that this attribute is the primary key of this entity.
@GeneratedValue(strategy = GenerationType.IDENTITY) : Informs the persistence layer that the strategy used to generate the
value of our primary key is by auto-increasing when a new user is created.
As for the rest, this is when Lombok starts to show up in our application.
@Data : Creates toString, equals, hashCode, getters and setters methods for our class.
Next step is creating our UserRepository interface which will extend JpaRepository to access the methods necessary to manipulate
the User table.
We’ll also need to pass the class that represents our model and the type of the primary key as generic arguments.
src/main/java/com/usersapi/domain/user/UserRepository.java
@Repository
public interface UserRepository extends JpaRepository<User, Long> {}
https://medium.com/swlh/building-a-crud-restful-api-web-service-with-spring-boot-a4f29edfbcd3 3/16
14/04/2024, 22:05 Building a CRUD RESTful API/Web Service with Spring Boot | by Gabriel Pulga | The Startup | Medium
The @Repository annotation is from Spring and its purpose is simply to indicate that the class provides the mechanism for
storage, retrieval, search, update and delete operation on objects.
Configuration of our in-memory database and inputting initialization example data into User table
In our src/main/resources/application.properties file, we’ll need to specify the data source for our Spring application.
spring.datasource.url=jdbc:h2:mem:usersapi
jdbc : Stands for Java Database Connectivity, it’s a set of class and interfaces written in Java to send SQL instructions to any
operational database.
To create initialization example data for our User class, we’ll need to create a data.sql file and input our data there.
src/main/resources/data.sql
Create : When given a valid HTTP POST request in /users, create a specific user.
Detail : When given a valid HTTP GET request in /users/{id}, retrieve the details of a specific user by its id.
List : When given a valid HTTP GET request in /users, retrieve the details of all users.
Update : When given a valid HTTP PUT request in /users/{id}, update the details of a specific user by its id.
Delete : When given a valid HTTP DELETE request in /users/{id}, delete a specific user by its id.
src/main/java/com/usersapi/endpoints/create/CreateUserService.java
@Service
public class CreateUserService {
@Autowired
UserRepository repository;
public User createNewUser(User user) {
return repository.save(user);
}
}
@Autowired : Our dependency injection annotation, autowiring our application is fundamental when building it.
Search
https://medium.com/swlh/building-a-crud-restful-api-web-service-with-spring-boot-a4f29edfbcd3 4/16
14/04/2024, 22:05 Building a CRUD RESTful API/Web Service with Spring Boot | by Gabriel Pulga | The Startup | Medium
src/main/java/com/usersapi/endpoints/create/CreateUserController.java
@RestController
@RequestMapping(“/users”)
public class CreateUserController {
@Autowired
CreateUserService service;
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public ResponseEntity<User> createNewUser_whenPostUser(@RequestBody User user) {
User createdUser = service.createNewUser(user);
@RestController : Combines the @Controller and @ResponseBody annotations, which eliminates the need to annotate every
request handling method of the controller class with @ResponseBody.
@RequestMapping(“/users”) : The main purpose of this annotation here is implementing our URL handler but it could also
map our HTTP request onto our method if it wasn’t already being done by the @PostMapping.
@ResponseStatus : Straightforward way to set the status code of our HTTP response.
@RequestBody : Ties our method parameter to the body of our HTTP request. This annotation indicates that the return type
should be written straight to the HTTP response body (and not interpreted as a view name).
src/main/java/com/usersapi/endpoints/detail/DetailUserService.java
@Service
public class DetailUserService {
@Autowired
UserRepository repository;
}
}
}
https://medium.com/swlh/building-a-crud-restful-api-web-service-with-spring-boot-a4f29edfbcd3 5/16
14/04/2024, 22:05 Building a CRUD RESTful API/Web Service with Spring Boot | by Gabriel Pulga | The Startup | Medium
No new annotations here. Our UserNotFoundException method will come from the following :
src/main/java/com/usersapi/endpoints/detail/UserNotFoundException.java
When an UserNotFoundException is thrown, this extra tidbit of Spring MVC configuration will be used to render an HTTP 404
response.
src/main/java/com/usersapi/endpoints/detail/UserNotFoundAdvice.java
@ControllerAdvice
public class UserNotFoundAdvice {
@ResponseBody
@ExceptionHandler(UserNotFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
String userNotFoundHandler(UserNotFoundException ex) {
return ex.getMessage();
}
}
@ResponseBody : Signals that this advice is rendered straight into the response body.
As for our Controller, if the contact is found, we’ll return it with a HTTP 200 response.
src/main/java/com/usersapi/endpoints/detail/DetailUserController.java
@RestController
@RequestMapping(“/users/{id}”)
public class DetailUserController {
@Autowired
DetailUserService service;
@GetMapping
@ResponseStatus(HttpStatus.OK)
public ResponseEntity<Optional<User>> listUser_whenGetUser(@PathVariable Long id) {
return ResponseEntity.ok().body(service.listUser(id));
}
}
@GetMapping : Similar to the @PostMapping annotation, maps our GET request onto our method.
When listing or retrieving all users, no exceptions will need to be handled, so this can be done by simply calling the repository.
https://medium.com/swlh/building-a-crud-restful-api-web-service-with-spring-boot-a4f29edfbcd3 6/16
14/04/2024, 22:05 Building a CRUD RESTful API/Web Service with Spring Boot | by Gabriel Pulga | The Startup | Medium
src/main/java/com/usersapi/endpoints/list/ListUserService.java
@Service
public class ListUserService {
@Autowired
UserRepository repository;
public List<User> listAllUsers() {
return repository.findAll();
}
src/main/java/com/usersapi/endpoints/list/ListUserController.java
@RestController
@RequestMapping(“/users”)
Next, we’ll find the user that needs to be updated and save it with its new parameters. Our Service class should be something like :
src/main/java/com/usersapi/endpoints/update/UpdateUserService.java
@Service
public class UpdateUserService {
@Autowired
UserRepository repository;
public User updateUser(Long id, User user) {
Optional<User> userOptional = repository.findById(id);
if (!userOptional.isPresent()) {
throw new UserNotFoundException(id);
} else {
repository.findById(id);
return repository.save(user);
}
}
}
As for building our Controller it should be pretty straightforward by now, since our Service contains the logic behind our
endpoint implementation.
https://medium.com/swlh/building-a-crud-restful-api-web-service-with-spring-boot-a4f29edfbcd3 7/16
14/04/2024, 22:05 Building a CRUD RESTful API/Web Service with Spring Boot | by Gabriel Pulga | The Startup | Medium
All we need to do is pass our soon to be changed user and its id as parameters, also the @PutMapping annotation to handle the
HTTP request.
src/main/java/com/usersapi/endpoints/update/UpdateUserController.java
@RestController
@RequestMapping(“/users/{id}”)
public class UpdateUserController {
@Autowired
UpdateUserService service;
@PutMapping
@ResponseStatus(HttpStatus.OK)
public ResponseEntity<User> updateUser_whenPutUser(@RequestBody User user, @PathVariable Long id) {
return ResponseEntity.ok().body(service.updateUser(id, user));
}
src/main/java/com/usersapi/endpoints/delete/DeleteUserService.java
@Service
public class DeleteUserService {
@Autowired
UserRepository repository;
public void deleteUser(Long id) {
Optional<User> userOptional = repository.findById(id);
if (!userOptional.isPresent()) {
throw new UserNotFoundException(id);
} else {
repository.deleteById(id);
}
}
}
src/main/java/com/usersapi/endpoints/delete/DeleteUserController.java
@RestController
@RequestMapping(“/users/{id}”)
public class DeleteUserController {
@Autowired
DeleteUserService service;
@DeleteMapping
@ResponseStatus(HttpStatus.NO_CONTENT)
Endnotes
Throughout this tutorial, you have engaged in various steps to build a RESTful API/Web Service with CRUD operations, our next
steps with this will be :
Implementing Swagger in our API for documentation and quick interface purposes.
Unit testing our endpoints controllers and services with JUnit and Mockito.
Source code
Available on our github page here.
If you’d like to visit the Linkedin of the people that wrote this tutorial : Gabriel and Gibran.
Bean Scopes in Java Spring Boot: RequestEntity Spring Boot Project save How Spring Boot I
Springboot vs ResponseEntity |… the precious time of… Annotations Works B
8 min read · Oct 7, 2022 4 min read · Feb 4, 2023 1 min read · Jun 12, 2023 4 min read · Sep 3, 2023 7
View list
Follow
https://medium.com/swlh/building-a-crud-restful-api-web-service-with-spring-boot-a4f29edfbcd3 9/16
14/04/2024, 22:05 Building a CRUD RESTful API/Web Service with Spring Boot | by Gabriel Pulga | The Startup | Medium
Gabriel Pulga
Building a Real Time Chat Application with Spring Boot and Websocket
In this article, you’ll learn how to use WebSocket along with Spring Boot and build a simple group chat application.
135
What Sam Altman’s Prediction About The $1B One-Person Business Model Means For You
If you’re under 39, you’ve got a massive advantage.
5.1K 146
https://medium.com/swlh/building-a-crud-restful-api-web-service-with-spring-boot-a4f29edfbcd3 10/16
14/04/2024, 22:05 Building a CRUD RESTful API/Web Service with Spring Boot | by Gabriel Pulga | The Startup | Medium
How Silently Building Apple Vision Pro Apps Can Make You Miserably Wealthy
Let me show you (exactly) how tomorrow’s millionaires are made.
1.5K 22
Gabriel Pulga
A Beginners Guide to Unit Testing CRUD Endpoints of a Spring Boot Java Web Service/API
Learn how to implement unit tests in a web services endpoints with this in depth how to guide
120
https://medium.com/swlh/building-a-crud-restful-api-web-service-with-spring-boot-a4f29edfbcd3 11/16
14/04/2024, 22:05 Building a CRUD RESTful API/Web Service with Spring Boot | by Gabriel Pulga | The Startup | Medium
Gagan Jain
11
https://medium.com/swlh/building-a-crud-restful-api-web-service-with-spring-boot-a4f29edfbcd3 12/16
14/04/2024, 22:05 Building a CRUD RESTful API/Web Service with Spring Boot | by Gabriel Pulga | The Startup | Medium
Vishamber Lal
18 1
Lists
https://medium.com/swlh/building-a-crud-restful-api-web-service-with-spring-boot-a4f29edfbcd3 13/16
14/04/2024, 22:05 Building a CRUD RESTful API/Web Service with Spring Boot | by Gabriel Pulga | The Startup | Medium
Kavinda Dissanayake
Abishan Parameswaran
https://medium.com/swlh/building-a-crud-restful-api-web-service-with-spring-boot-a4f29edfbcd3 14/16
14/04/2024, 22:05 Building a CRUD RESTful API/Web Service with Spring Boot | by Gabriel Pulga | The Startup | Medium
Gnanadeep Vetukuri
Getting Started with Java — Spring Boot Backend with MySQL Database for Web App Development
Introduction to Java for Web App Development:
11
Isaac Tonyloi
https://medium.com/swlh/building-a-crud-restful-api-web-service-with-spring-boot-a4f29edfbcd3 15/16
14/04/2024, 22:05 Building a CRUD RESTful API/Web Service with Spring Boot | by Gabriel Pulga | The Startup | Medium
https://medium.com/swlh/building-a-crud-restful-api-web-service-with-spring-boot-a4f29edfbcd3 16/16