Fully Functional Spring Boot CRUD REST API Under 50 lines of Kotlin

Author: Shazin Sadakath


Kotlin is an upcoming programming language introduced by IntelliJ. It is becoming famous for its concise syntax which eliminates alot of boiler plate code. I have already introduced the Kotlin language in a previous article, but in this article I will use it with Spring Boot to build a Fully Functional CRUD REST API in under 50 lines of Kotlin Code.

First of all I can use start.spring.io to generate the Spring Boot project for Maven along with the dependencies required for this project. In our case I need Web, Spring Data JPA, etc. The complete source code is available at GitHub.

I have enabled Swagger UI by adding necessary dependencies so all the Endpoints created will be visible and able to access using the urlĀ http://localhost:8080/swagger-ui.html. The domain for this implementation will be a simple Book repository which can be accessed and modified using the CRUD REST API.

Following is the source code in Kotlin that's all there is to it. It is 47 lines including the package descriptor and imports.

package lk.techtalks.kotlin.demo

import org.springframework.boot.SpringApplication
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.data.domain.Pageable
import org.springframework.data.jpa.repository.JpaRepository
import org.springframework.data.web.PageableDefault
import org.springframework.web.bind.annotation.*
import springfox.documentation.swagger2.annotations.EnableSwagger2
import javax.persistence.*
import javax.validation.constraints.NotNull

@SpringBootApplication
@EnableSwagger2
class Application

fun main(args: Array) {
    SpringApplication.run(Application::class.java, *args)
}

@Entity
@Table(name = "book")
class Book(@Id @GeneratedValue(strategy = GenerationType.IDENTITY) var id : Long, @NotNull var title : String, var isbn : String? = null, @NotNull var author : String) {
    constructor() : this(0L, "", null, "")
}

interface BookRepository : JpaRepository

@RestController
@RequestMapping("/books")
class BookController(var bookRepository: BookRepository) {

    @GetMapping
    fun get(@PageableDefault(size = 10, page = 0) pageableDefault: Pageable) = bookRepository.findAll(pageableDefault);

    @PostMapping
    fun post(@RequestBody book : Book) = bookRepository.save(book);

    @DeleteMapping("/{id}")
    fun delete(@PathVariable id : Long) = bookRepository.delete(id);

    @PutMapping("/{id}")
    fun put(@PathVariable id : Long, @RequestBody book: Book) {
        book.id = id;
        bookRepository.save(book)
    }
}

You can see the power of syntax in Kotlin and this code will be compiled to Java byte which can be run in a JVM without any problem.



Tags: Kotlin REST SpringBoot CRUD
Views: 412

Comments

Please login or register to post a comment.


There are currently no comments.