Spring Data REST
Learn how to create a REST API with full CRUD functionality without writing any controller or service layer code using Spring Data REST.
Spring Data REST is a project similar to Spring Data JPA which aims to eliminate boilerplate code. With Spring Data JPA, we get the basic CRUD functionality without writing any code simply by specifying the entity and the type of primary key. Similarly, Spring Data REST provides a REST API based on the repository and entity without us having to write any code in the controller and service layer.
Spring Data REST uses the repository to expose endpoints to perform GET, POST, PUT, PATCH and DELETE on every entity in the application. Spring Data REST works with data sources implementing the repository programming model. It supports Spring Data JPA, Spring Data MongoDB, Spring Data Cassandra as well as other Spring Data projects. In the image below, it eliminates the need for PlayerController
and PlayerService
classes.
Spring Data REST provides a basic REST API which can be customized. Custom queries can be added using JPQL and Query DSL.
Earlier, we saw how to implement a Tennis Player REST API. We had a Player
entity and created a PlayerRepository
implementing the JpaRespository
interface. Spring Data REST can provide us a similar API simply by scanning our repository and exposing the /players
endpoint.
Spring Data REST creates endpoints using the entity name by making the first letter lowercase and adding an ‘s’ to the end of the name. For the case shown below, Spring Data REST will convert the entity name Player
to its uncapitalized, pluralized form players
and expose the REST endpoints at /players
. It also exposes /players/{id}
for each item managed by the repository.
@Entitypublic class Player {//...}
To create a Spring Data REST application using Spring Boot, we need the following:
spring-boot-starter-data-rest
dependency inpom.xml
An entity (e.g.,
Player
)A repository interface (e.g.,
JpaRepository
orCrudRepository
) ...