It will not be an overstatement if I say that we canโt develop an enterprise application without using webservices as an integration layer. Generally, we develop webservices in the form of either a producer or a consumer or both. However Producer is very important for us because we develop it in Java only. Also, we have full control of database interaction logic implementation with us. Now you might have interpreted the significance of our article โHow to develop REST CRUD API using Spring Boot?โ. On the other hand, Consumer can be Angular Application, ReactJS Application, Android Device, iOS Device and many others or even our favorite java based RestTemplate(Spring Boot REST Client).
Building a RESTful CRUD (Create, Read, Update, Delete) API is a common task in modern web development. Spring Boot, a powerful and modernized framework, makes this process straightforward. Our focus in this article is on developing producer API(REST API) using Spring Boot. Now letโs discuss on โHow to develop REST CRUD API using Spring Boot ?โ without leaving any theoretical concept which are very essential to know.
What will you learn from this article?
Once you complete going through all points of this article, You will be able to answer :
1) What is REST and REST API in the context of Web services?
2) How to create a Spring Boot REST application that incorporates industry level project design ?
3) How to develop CRUD (Create, Retrieve, Update, Delete) operations that can be used by any other even non-java application ?
4) How to write bug free CRUD operations, including exceptions & exception handlers?
5) Equally important, How to use annotations @RestController, @RequestMapping, @GetMapping, @PostMapping, @PutMapping, @DeleteMapping, @PatchMapping, @Modifying, @Query, @Transactional, @RestControllerAdvice, @ExceptionHandler, @ControllerAdvice, @ResponseBody, @RequestBody, @PathVariable, @Data, @NoArgsConstructor, @AllArgsConstructor, @Entity, @Component, @Service, @Autowired ?
6) How to work with Spring Boot Data JPA repository interface?
7) How to write modular & reusable code?
8) Moreover, How to implement dynamic code with minimal changes, keeping future change requests in mind?
9) How to develop an integration layer to get interoperability ?
10) How to test REST Application by supplying & receiving JSON data ?
11) Last but not the least you will learn โHow to develop REST CRUD API using Spring Boot ?โ
What is REST?
REST stands for Representational State Transfer. It transfers state(data) in global format(representational) between two different applications running on different servers. In the process of data transfer, who requests data is called Consumer/Client application and who provides data is called a producer application. REST is an architectural style that follows a set of rules to create webservices. Webservices provide reusable data to multiple applications and interoperability between them on the internet. Web services that conform to the REST architectural style, called RESTful Web services.
How to develop REST CRUD API using Spring Boot ?
Developing a Rest API is nothing but creating classes & methods in a specific architectural style so that data can be reused between interoperable applications. More or less we create RestController and respective CRUD operations in the process of development of the REST API.
What is RestController ?
In Spring Boot REST programming RestController is a mandatory class which acts as a front controller. It contains several methods that return Body and Status as a ResponseEntity object. Body refers to data in form of String, Object, Collections etc. Whereas Status refers to the HttpResponse Status (200, 404,405, 500 etc.).
Software used in this Project ?
โSTS (Spring Tool Suite) : Version-> 4.7.1.RELEASE
โMySQL Database : Version ->8.0.19 MySQL Community Server
โJDK8 or later versions (Extremely tested on JDK8, JDK9 and JDK14)
Coding Steps
Step#1 : Create Project in STS
If you are new to Spring Boot, visit a separate article on how to create a sample project in spring boot. While creating project in STS add 4 starters โMySql Driverโ, โSpring Data JPAโ, โSpring Webโ and โLombokโ. You can also add โSpring Boot DevToolsโ optionally. If you are new to โLombokโ, kindly visit โHow to configure Lombokโ and to know all about it in detail.
Step#2 : Create Databaseย
You can use database software of your own choice and create a Database accordingly. We have used MySQL database software. Login to your MySQL and execute a Database creation query. In our case DB Name is โREST_INVOICEโ, so our query will be โ CREATE DATABSE REST_INVOICEโ.
Step#3 : Update application.properties and Write Classes & methods(REST API)ย
Letโs consider โInvoiceโ as a model to develop the REST API. Invoice will have many fields such as invoiceNumber, invoiceName, invoiceAmount etc.. Below Table will show the list of classes & other files used in the project accordingly.
Package/Location | Class/Interface/file name | Purpose |
---|---|---|
src/main/resources | application.properties | properties file to declare common properties in the project |
com.dev.invoice.rest.entity | Invoice.java | Model/Entity class with Database table mapping |
com.dev.invoice.rest.repo | InvoiceRepository.java | Repository Interface which extends JpaRepository |
com.dev.invoice.rest.service | IInvoiceService.java | Service interface with Database related methods |
com.dev.invoice.rest.service.impl | InvoiceServiceImpl.java | Service class contains implementations of methods declared in Service interface for Database related operations |
com.dev.invoice.rest.entity | ErrorType.java | Helper class used in InvoiceErrorHandler.java |
com.dev.invoice.rest.exception | InvoiceNotFoundException.java | To define custom Exception if any Invoice not found |
com.dev.invoice.rest.exception.handler | InvoiceErrorHandler.java | To handle the error In case InvoiceNotFoundException is thrown from any controller method |
com.dev.invoice.rest.util | InvoiceUtil.java | Utility class to maximize code reusability & minimize code redundancy. |
com.dev.invoice.rest.controller | InvoiceRestController.java | Rest Controller the backbone of REST API, accepts all requests coming from client and handover to respective method for processing. |
This POJO class representing an entity called โInvoiceโ uses JPA (Java Persistence API) annotations for object-relational mapping.
-
Annotations: The class uses various annotations from the javax.persistence package to define the mapping of the class to a relational database.
-
Lombok Annotations: The @Data, @NoArgsConstructor, and @AllArgsConstructor annotations are from the Lombok library, which automatically generates boilerplate code for getters, setters, constructors, and other common methods.
-
@Entity: An annotation indicating that the class is a JPA entity, meaning it is associated with a table in the database.
-
@Id: An annotation used to specify the primary key of the entity.
-
@GeneratedValue: An annotation to specify that the ID should be automatically generated.
-
Attributes: The class has several attributes representing different properties of an invoice such as id, name, amount, finalAmount, number, receivedDate, type, vendor, and comments.
This class is designed to map invoice objects to a database table using JPA and Lombok annotations (to reduce boilerplate code).
Finally your project structure would look like below screen.
How to run the application ?
Further to run the application for testing purpose, right click on Project and then select Run As >> Spring Boot App. You can also package it into a jar & run it accordingly. Additionally, to test the app you need to have a Client application/software.
How to test the application ?
As discussed in introduction part, there are multiple ways to test the REST application. At this point, we will suggest you to use the most popular tool โPOSTMANโ. You can also download it from here.
โ Testing saveInvoice() method : [http://localhost:8080/api/invoices]
Open Postman software, Select method โPOSTโ from dropdown, enter below URL, select โBodyโ then click on โrawโ, select โJSONโ from dropdown. All the above selections are highlighted in the below screenshot. Now Enter data in JSON format. If you want to know more about json, visit a separate article on โhow to write data in JSON formatโ. Once you enter the JSON data, click on โSendโ button & check the successful message in the lower box.
http://localhost:8080/api/invoices
โฆ Testing getAllInvoices() method : [http://localhost:8080/api/invoices]
Select method โGETโ from dropdown, then enter below URL. Now click on โSendโ button & check the list of all invoices as a JSON format in lower box.
http://localhost:8080/api/invoices
โ Testing getOneInvoice() method : [http://localhost:8080/api/invoices/{id}]
{id} represents dynamic data. Suppose we want to retrieve Invoice whose id is 2. Select method โGETโ from dropdown, then enter below URL. Then click on โSendโ button & check the invoice with given id as a JSON format in lower box.
http://localhost:8080/api/invoices/2
โฆ Testing updateInvoice() method : [http://localhost:8080/api/invoices/{id}]
Select method โPUTโ from dropdown, enter below URL, select โBodyโ then click on โrawโ, select โJSONโ from dropdown. Thereafter Enter data in JSON format to be modified. Then click on โSendโ button and check the successful message in lower box.
http://localhost:8080/api/invoices/2
โ Testing deleteInvoice() method : [http://localhost:8080/api/invoices/{id}]
Suppose you want to remove an Invoice where id is 2. Then use below pattern URL. Select method โDELETEโ from dropdown, then enter below URL. Then click on โSendโ button and check the successful message in lower box.
http://localhost:8080/api/invoice/2
โฆ Testing updateInvoiceNumberById() method : [http://localhost:8080/api/invoices/{id}/{number}]
Suppose you want to modify name field of an Invoice where id is 1. Then use below pattern URL. Select method โPATCHโ from dropdown, enter below URL, select โBodyโ then click on โrawโ, select โJSONโ from dropdown. Then Enter data in JSON format to be modified. Finally click on โSendโ button & check the successful message in lower box.
http://localhost:8080/api/invoices/1/Inv02345
Can we use this REST API example in the real project ?
Of course. You have to change all occurrences of Entity Name as per your real project, then you may use it accordingly.
FAQ
How can I define API endpoints in Spring Boot?
API endpoints are defined by creating controller classes in Spring Boot. These classes use annotations like @RestController and @RequestMapping to map HTTP methods (GET, POST, PUT, DELETE) to specific Java methods that handle the requests.
What is the role of the @ResponseBody annotation in Spring Boot REST controllers?
The @ResponseBody annotation is used to indicate that the return value of a controller method should be serialized directly to the HTTP response body. It is often used when returning data is in JSON or XML format.
How can I document my Spring Boot REST API for developers and consumers?
We can document our Spring Boot REST API using tools like Swagger, Springfox, or OpenAPI. These tools generate interactive API documentation that helps developers and consumers understand how to use REST API.
How can I test my Spring Boot REST API endpoints?
We can test Spring Boot REST API endpoints using tools like Postman, curl, or by writing unit tests and integration tests using frameworks like JUnit and Spring Test. Moreover, we can write methods using RestTemplate to test the REST API endpoints.
What is the difference between PUT and PATCH methods, and when should I use each in Spring Boot REST APIs?
The PUT method updates or replaces an entire resource, while the PATCH method makes partial modifications to a resource. In Spring Boot REST APIs, we should use PUT when we need to update the entire resource, and PATCH when we want to apply partial updates accordingly.
Conclusionย
Almost every REST application will have these operations that we learnt in this article. To sum up, it is almost impossible to develop a REST API without having these operations. We have learnt the mandatory concepts of โHow to develop REST CRUD API using Spring Boot ?โ. Furthermore, you can go through other article on How to consume REST API using RestTemplate using Spring Boot.
ok
ok
I want to say that this post is awesome, great written and include almost all necessary information.
I would like to see more posts like this .
This is a topic thatโs near to my heartโฆ Cheers! Exactly where are your contact details though?
Always click on โContact Usโ to connect with us.
Really good article covering all the basics!
Really good article
Hey! I truly enjoy reading through your articles. Appreciate it!
Dear Website Creater,
Thank you for providing this Excellent article.
please provide the JUnit and Mockito test cases from basics and multiple test cases in multiple scinarios, because i was seraching many times on google, youtube about the multiple test case scinario but i canโt.
Please provide this article as soo as posiable.