Spring Boot REST API with Kotlin

Harry · 23 Sep 2026 · 3 views
Log in to track your progress and mark lessons complete.

Project Setup

start.spring.io with Kotlin, Web, JPA, Validation, H2. Kotlin plugin plus kotlin("plugin.spring") (opens classes for proxies) and kotlin("plugin.jpa") (no-arg constructors) are preconfigured.

Entity and Repository

@Entity
class Book(
    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
    var id: Long = 0,
    @field:NotBlank var title: String = "",
    var price: Int = 0
)
interface BookRepository : JpaRepository<Book, Long> {
    fun findByTitleContainingIgnoreCase(q: String): List<Book>
}

Controller

@RestController
@RequestMapping("/api/books")
class BookController(private val repo: BookRepository) {
    @GetMapping fun all() = repo.findAll()
    @PostMapping @ResponseStatus(HttpStatus.CREATED)
    fun create(@Valid @RequestBody b: Book) = repo.save(b)
}

Kotlin-Specific Gotchas

  • Constructor injection with val is the default style.
  • Validation annotations target fields: @field:NotBlank.
  • Data classes as JPA entities need the no-arg plugin (already added by Initializr).
  • Null safety plus validation equals APIs that reject bad input twice.

Kotlin Spring REST controller with constructor injection

Key Points

  • Initializr handles the Kotlin plugin wiring.
  • Controllers read like pseudocode with constructor injection.
  • Same testing stack: MockMvc plus Mockk or Mockito.
Share this post:

Comments (0)

Please login or register to comment.

Create a free account to keep reading

You've enjoyed a free tutorial! Register (it's free) to unlock every tutorial, track your progress and save code.

or sign in with your account

Already have an account? Log in