Quick REST APIS with Spring Data Rest
Spring Data Rest is a quite powerful if we are just trying to provision CRUD REST endpoints for the data entities. Once the data model and the associated spring data repository is defined, Spring Data Rest exposes CRUD REST endpoints for these data repositories out of the box. These endpoints can be secured with Spring Security and further customised to exclude certain operations for an entity, exclude certain fields, apply paging and sorting, validations and pre and post events to make more enterprise grade solution beyond MVP.
The example in repo uses following entities with H2 in memory database.
@Entity
open class Address(
@Id
@GeneratedValue(strategy = GenerationType.AUTO) open var id: Long? = null,
open var street: String,
open var suburb: String,
open var state: String,
open var country: String
)
@Entity
open class Customer(
@Id
@GeneratedValue(strategy = GenerationType.AUTO) open var id: Long? = null,
open var firstName: String,
open var lastName: String,
@OneToOne(cascade = [CascadeType.ALL])
@JoinColumn(name = “address_id”, referencedColumnName = “id”)
open var address: Address? = null
)
@RepositoryRestResource
interface AddressRepository: CrudRepository<Address, Long>
@RepositoryRestResource
interface CustomerRepository: CrudRepository<Customer, Long>
With the following dependencies
dependencies {
implementation("org.springframework.boot:spring-boot-starter-data-jpa")
implementation("org.springframework.boot:spring-boot-starter-data-rest")
implementation("org.springframework.boot:spring-boot-starter-webflux")
implementation("com.fasterxml.jackson.module:jackson-module-kotlin")
implementation("io.projectreactor.kotlin:reactor-kotlin-extensions")
implementation("org.jetbrains.kotlin:kotlin-reflect")
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-reactor")
implementation("org.springframework.data:spring-data-rest-hal-explorer")
runtimeOnly("com.h2database:h2")
testImplementation("org.springframework.boot:spring-boot-starter-test")
testImplementation("io.projectreactor:reactor-test")
developmentOnly("org.springframework.boot:spring-boot-devtools")
}
when the application is launched, the HAL browser can be accessed at
http://localhost:8080 to explore the entities via the REST apis.
Code repository for the sample project https://github.com/achalise/spring-data-rest-sample