Spring Boot Guide for Beginner: CRUD
Guide for handling many HTTP Request: GET, POST, PUT, DELETE
Many projects sometimes separate backend and frontend services. It is an excellent practice to do separation of concern due to the security and maintainability of each service.
However, the problem that follows this approach is how to connect those services and make them talk. The frontend needs to access resources from the backend while using only the backend alone will frustrate the users.
This condition is where HTTP Requests come into play. Internet Engineering Task Force (IETF) made RFC 2616 that standardizes communicating to a hosting service. The document defines HTTP Request Methods for each typical web transaction.
These web transactions are collectively called CRUD operations, an acronym for Create, Read, Update, and Delete. The relationship between CRUD operations and HTTP Requests are described as follows:
- To create information, use the HTTP POST method.
- To read information, use the HTTP GET method.
- To update information, use the HTTP PUT method.
- To delete information, use the HTTP DELETE method.
This article will is a guide for implementing CRUD operations in Spring Boot. One of the benefits of using Spring Boot is its autoconfiguration. So, you don’t have to worry about anything more than your business logic. The goal of this article is we wanted to do create, read, update, and delete operations on an Guest
entity/model.
Prerequisite
In this instruction, few dependencies are needed and will not be covered by this article. Nevertheless, an external link for the instruction to install them is provided as a hyperlink below:
- JDK 1.8
- IntelliJ IDEA
- Postman or any API testing tools
Hands-On Learning
The starter code is provided by the link here to make it easier to get up and run. However, it is optional. You can always generate the starter code by yourself using Spring Initialzr. Moreover, develop your own starter code if you prefer to use other Java versions or add additional dependencies. I have an article covering this matter; Please, go check it out.
Make a New Documents
After cloning the repository (or generating your own starter code), open the source code using IntelliJ IDEA or any IDE of your choice. Then, navigate into src/main/java/com/andhikayusup/learncrud
the folder, where you do most of your work there. Make a new package/folder using IntelliJ IDEA by right-clicking on the parent folder then navigating to new -> Package
. You can follow the preceding instruction by the gif below.
After generating the guest
folder, you will need to create additional files to follow up on this article. IntelliJ IDEA makes it easy to generate Java Class by right-clicking the guest
folder and navigating to new -> Java Class
. This action will produce Java Class with some pre-filled template codes ready. You can follow the preceding instruction by the gif below.
To deliver a better code, we need to distribute production code into separate files so that each file has its own collective function. We can divide our implementation of CRUD operations into three files: Guest
, GuestService
, and GuestController
.
In the OOP paradigm, we modeled the world as the interaction of Objects. A Class is a template for our Objects, and it defines default properties and methods. The first file we create is Guest.java
which function as a Class for our problem. For this case, we have a Guest
class with several properties and methods. The properties of this class are ID
, full name
, and age
; meanwhile, the methods are the setter and getter for each property. The final code for this file should look like this:
The second file that we generate is GuestService
. This is the file that should be the implementation of our business logic. We do not use stored databases like PostgreSQL for now; we will keep Guest
objects as an ArrayList in our server in-memory. So, This file will implement the business logic of creating, retrieving, updating, and deleting those objects into our defined ArrayList.
The code above has @Component
annotations for our GuestService
class. This annotation tells Spring Boot to instantiate them wherever we do dependency injection. Dependency Injection is one of Spring Boot’s advantages because it removes decoupling between classes. Amigoscode has a great video explaining this matter on his video here.
REST Controller
The third file that we should implement is GuestController
. @RestController
annotation used on this class tells Spring Boot that the class will be the REST Controller, the entry point for our services. In addition, @RequestMapping(<path>)
is used to map at what path the said REST Controller controls a request. This REST Controller class will accept the request at api/v1/guest
path for this problem.
Remember the @Component
annotation that we declared on GuestService.java
? We will instantiate the GuestService
using dependency injection on this class. To perform this action, first, we need to implement the constructor of GuestController
class with the GuestService
object as its parameters. Then, we use @Autowired
annotation to indicate Spring Boot that we used dependency injection.
Handle GET Request
HTTP GET method is commonly used to read data from the hosting service. @GetMapping
is used to indicate that said method is a handler for the GET request method.
The implementation of this handler is quite simple. We just need to return the output of the getGuests
method that we defined in the GuestService
class.
Handle POST Request
A method has to use @PostMapping
annotation so that Spring Boot can tell that this method is a handler for POST requests.
The goal of this method is to save guest information from a user into the system. We decided to require users to put their data in the Request Body. Spring Boot made it easy to extract all the information provided by the user in the Request Body directly into an instance of Guest
class.
This can be done by attaching @RequestBody
annotations into a parameter. Then, call the addGuest
method in GuestService
class to insert those data into our (in-memory) database. Last, we need to return that instance to our user to be processed further by frontend services.
Handle DELETE Request
If we wanted to instruct to delete a piece of information on our service, the HTTP DELETE Request method is the proper method for performing. A method uses @DeleteMapping(<Path>)
annotation so that Spring Boot can tell that this method is a handler for DELETE Requests. We design the API path so that we include additional information for our target guest
ID number. Retrieving information in that API path is easy. We just need to put the @PathVariable(<var>)
method into the function parameter.
Then, we pass those guest
ID into the deleteGuest
method in GuestService
class as the parameter to perform information deletion. This function does not return any data, so the best practice is to tell our user a 204 No Content
response status.
Handle PUT Request
A method has to use @PutMapping
annotation so that Spring Boot can tell that this method is a handler for HTTP PUT Requests. Same as HTTP DELETE Request, we also put guest
id information in our path variable. In addition, We also need other information on our path variable as a Request Parameter. To be able to do this, we should put @RequestParams(required=false)
annotations to target parameters. The difference between Request Parameter and Path Variable is we can set Request Parameter to optional.
Although the end result is must not be the same, if you follow this article instruction, the final code of GuestController.java
should be look like the picture below:
Result
If you follow this guide up to this section, congratulations! You just need to run the application so that we can test our service. We are going to perform CRUD operation to the service using Postman. I shared the API collection so you can just import it to Postman by the link below.
https://www.getpostman.com/collections/14480a416e8c1e3d9963
Follow this GIF below to test our web application using Postman API Testing tools:
Further Reading
This is a simple guide for developing CRUD operations on Spring Boot. There are a lot of improvements that you should make. I have put external links below for you to learn other improvements and components in Spring Boot:
- Securing applications with JWT Spring Boot by Ignacio Oliveto
- Building a Microservice with Spring Boot and Spring Cloud bt Clover Platform
- GraphQL with Java and Spring Boot by Tiago Albuquerque
Special shout out to Amigoscode. His great and easy-to-understand content really help me to understand Spring Boot. Please go check his Youtube channel and don’t forget to subscribe.