How to reduce boilerplate code in REST API Spring Data REST java Spring Spring Boot Spring Boot REST Spring Data REST by devs5003 - October 20, 2023July 23, 20245 Last Updated on July 23rd, 2024In previous article on REST API Development, we have already seen that how we can develop a REST API with minimum lines of code. Still, we have more scope to reduce lines of code using a concept called ‘Spring Data REST’ in Spring Boot. So, our title of the article is ‘How to reduce boilerplate code in REST API Spring Data REST’. In Spring Data REST concept we don’t have to write even RestController and its methods. The Spring Data REST dependency will take care of it using HATEOAS (Hypertext as the Engine of Application State). HATEOAS project is a library of APIs that we can use to easily create REST representations. Spring Data REST provides hyperlinks to access REST operations with the help of HATEOAS only. When some details of a resource are requested, you will provide the resource details as well as details of related resources and the possible actions you can perform on the resource. HATEOAS provides us this type of details. You might have guessed that we will learn Spring Data REST concepts using Spring Boot only. Let’s start learning ‘How to reduce boilerplate code in REST API Spring Data REST’. Table of Contents Toggle What is Spring Data REST ?How to configure Spring Data REST in Spring Boot Project ?Where can we use Spring Data REST Concept ?Coding Steps: How to reduce boilerplate code in REST API Spring Data REST?Step #1 : Create Spring Boot Starter ProjectStep #2 : Add dependencies in Spring Boot Starter ProjectStep #3 : Write Model/Entity classStep #4 : Write Repository InterfaceStep #5 : Update application.properties fileHow to test the created REST API using Spring Data REST ?Step #1 : Run the created Spring Boot Starter ProjectStep #2 : Enter the URL as http://localhost:8080/ into Browser.Step #3 : Create URL for CRUD operationsStep #4 : Test the created API What is Spring Data REST ? Spring Data REST is a concept which minimizes a lot of manual work and provides basic implementation of CRUD functionality quite easy. It is built on top of Spring Data Project and also comes under the umbrella Spring Data Project. How to configure Spring Data REST in Spring Boot Project ? If you are using Maven tool, you need to add below dependency in your pom.xml which is the main dependency of our project. You will get feature of Spring Data REST from this dependency only. It’s very easy to add if you are using Spring Boot Starter Project. You will find the same in steps given in below sections. <dependencies> ... <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-rest</artifactId> </dependency> ... </dependencies> Where can we use Spring Data REST Concept ? The applications which require only CRUD operations, we can use this concept to generate REST API and get rid of boilerplate codes. As mentioned earlier using this concept we can reduce not only the boilerplate code, but also get rid of memorizing the annotations at Controller and method levels. Coding Steps: How to reduce boilerplate code in REST API Spring Data REST? Step #1 : Create Spring Boot Starter Project If you are new in creating Spring Boot Starter Project, follow a separate tutorial on ‘How to create a starter project using STS?‘. Step #2 : Add dependencies in Spring Boot Starter Project Spring Data JPA -> to use JPA repository interfaces Rest Repositories -> to use Spring Data REST features (Main part of our project) MySQL Driver -> to get use of MySQL Database Lombok -> to avoid lots of boilerplate code, for more info you may follow internal link on Lombok. Spring Boot DevTools -> to avoid restarting tomcat every time we change in the code If you are using Maven tool, you can check the below dependency in your pom.xml which is the main dependency of our project. As mentioned earlier, you will get features of Spring Data REST from this dependency only. <dependencies> ... <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-rest</artifactId> </dependency> ... </dependencies> spring-boot-starter-data-rest <dependencies> ... <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-rest</artifactId> </dependency> ...</dependencies> Step #3 : Write Model/Entity class In order to generate the API, we are considering our previous entity ‘Invoice’. Invoice.java package com.dev.invoice.rest.entity;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.Id;import lombok.Data;@Data@Entitypublic class Invoice { @Id @GeneratedValue private Long id; private String name; private Double amount; private Double finalAmount; private String number; private String receivedDate; private String type; private String vendor; private String comments;} Step #4 : Write Repository Interface Interface InvoiceRepository extends from CrudRepository. InvoiceRepository.java package com.dev.invoice.rest.repo;import org.springframework.data.repository.CrudRepository;import com.dev.invoice.rest.entity.Invoice;public interface InvoiceRepository extends CrudRepository<Invoice, Long> { } Step #5 : Update application.properties file application.properties # DB Connection Propertiesspring.datasource.driver-class-name=com.mysql.cj.jdbc.Driverspring.datasource.url=jdbc:mysql://localhost:3306/REST_INVOICEspring.datasource.username=rootspring.datasource.password=devs# JPA Properitesspring.jpa.show-sql=truespring.jpa.hibernate.ddl-auto=updatespring.jpa.database-platform=org.hibernate.dialect.MySQL8Dialect That’s all for the coding part we need to write. Now observe how simple it is !!! How to test the created REST API using Spring Data REST ? Step #1 : Run the created Spring Boot Starter Project To run the application right click on Project and select Run As >> Spring Boot App. Step #2 : Enter the URL as http://localhost:8080/ into Browser. Once you enter the above URL and click enter, you will see the below output. localhost:8080/ { _links: { invoices: { href: "http://localhost:8080/invoices" }, profile: { href: "http://localhost:8080/profile" } } } The above output indicates that your URL for REST API will be ‘http://localhost:8080/invoices’. The point to observe here is that it has taken ‘invoices’ in the path from the entity name (Invoice), converts the first letter to lowercase & adds suffix ‘s’. Step #3 : Create URL for CRUD operations Below URLs will work perfectly for the created REST API. Base URL = http://localhost:8080/invoices GET URL : http://localhost:8080/invoices [to get all Invoices] GET URL : http://localhost:8080/invoices/{id} [to get invoice with a particular id] POST URL: http://localhost:8080/invoices [for saving invoices] PUT URL : http://localhost:8080/invoices/{id} [to modify an Invoice with a particular id] DELETE URL : http://localhost:8080/invoices/{id} [to delete an Invoice with a particular id] Step #4 : Test the created API One of the best and easiest way to test the REST API is to use ‘POSTMAN’ software. If you need more details on testing, go through a separate article on ‘How to test REST API using POSTMAN?‘ For more details on Spring Data & It’s sub-modules, kindly visit spring.io. If you are in search of a good book, to get a best deal kindly visit books for Programming Languages. Related
Hmm is anyone else having problems with the images on this blog loading? I’m trying to figure out if its a problem on my end or if it’s the blog. Any suggestions would be greatly appreciated. Reply
Hey there are using WordPress for your blog platform? I’m new to the blog world but I’m trying to get started and create my own. Do you need any html coding expertise to make your own blog? Any help would be really appreciated! Reply