REST API Example With Kotlin And Spring Boot And H2

Let’s create a simple application with three REST APIs
– to get all books
– to get a book by id
– to add a new book

Here is the project explorer:

Here is the full code:

https://github.com/afsinka/kotlin_springboot_h2_rest

package com
import org.springframework.boot.SpringApplication
import org.springframework.boot.autoconfigure.SpringBootApplication
@SpringBootApplication
class Application
fun main(args: Array<String>) {
SpringApplication.run(Application::class.java, *args)
}
view raw Application.kt hosted with ❤ by GitHub
spring:
h2:
console:
enabled: true
path: /h2
datasource:
url: jdbc:h2:mem:testdb
username: sa
password:
driverClassName: org.h2.Driver
#h2 console: http://localhost:8081/h2/
server:
port: 8081
view raw application.yml hosted with ❤ by GitHub
package com.model
import javax.persistence.Entity
import javax.persistence.Id
@Entity
data class Book(@Id val id:Long, val title:String)
view raw Book hosted with ❤ by GitHub
package com.repository
import com.model.Book
import org.springframework.data.repository.CrudRepository
interface BookRepository : CrudRepository<Book, Long> {
}
view raw Book Repository hosted with ❤ by GitHub
package com.controller
import com.model.Book
import com.service.BookService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.web.bind.annotation.*
@RestController
class BookController @Autowired constructor(
val bookService: BookService
) {
@GetMapping("/")
fun get(): List<Book> {
return bookService.getAll();
}
@GetMapping("/{id}")
fun get(@PathVariable(value = "id") id: Long): Book {
return bookService.get(id)
}
@PostMapping("/")
fun get(@RequestBody book: Book): Book {
return bookService.add(book)
}
}
view raw BookController hosted with ❤ by GitHub
package com.service
import com.exception.NotFoundException
import com.model.Book
import com.repository.BookRepository
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import java.util.Optional
@Service
class BookService @Autowired constructor(
val bookRepository: BookRepository
) {
fun getAll(): List<Book> {
return bookRepository.findAll().map { it };
}
fun get(id: Long): Book {
val book: Optional<Book> = bookRepository.findById(id).map { it }
return if (book.isPresent) {
book.get()
} else {
throw NotFoundException()
}
}
fun add(book: Book): Book {
return bookRepository.save(book)
}
}
view raw BookService hosted with ❤ by GitHub
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
plugins {
id("org.springframework.boot") version "2.4.0"
id("io.spring.dependency-management") version "1.0.10.RELEASE"
kotlin("jvm") version "1.4.10"
kotlin("plugin.spring") version "1.4.10"
kotlin("plugin.jpa") version "1.4.10"
}
group = "me.afsin"
version = "0.0.1-SNAPSHOT"
java.sourceCompatibility = JavaVersion.VERSION_11
repositories {
mavenCentral()
}
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-web")
implementation("com.fasterxml.jackson.module:jackson-module-kotlin")
implementation("org.jetbrains.kotlin:kotlin-reflect")
implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8")
implementation("com.h2database:h2")
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core")
testImplementation("org.springframework.boot:spring-boot-starter-test")
}
tasks.withType<Test> {
useJUnitPlatform()
}
tasks.withType<KotlinCompile> {
kotlinOptions {
freeCompilerArgs = listOf("-Xjsr305=strict")
jvmTarget = "11"
}
}
view raw build.gradle.kts hosted with ❤ by GitHub
package com.exception
import org.springframework.http.HttpStatus
import org.springframework.web.bind.annotation.ResponseStatus
@ResponseStatus(HttpStatus.NOT_FOUND)
class NotFoundException : RuntimeException()
view raw NotFoundException hosted with ❤ by GitHub
Tagged

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: