REST input validation with Spring Boot and Kotlin (youtube tutorial)

This blog post is for sharing the code from a Youtube video.

Input validation is important when developing a REST API. Thankfully Spring Boot has a starter dependency that makes the process straightforward. However if you are using Kotlin, there is pitfall that you need to be careful with. In this video we are going to a simple validation to a Kotlin project and also discuss the root cause of this pitfall.

package com.vladsave.firstboot

import org.springframework.web.bind.annotation.*
import javax.validation.Valid
import javax.validation.constraints.Size

data class ViewAccount(
    val id: Int,
    val name: String
)

data class CreateAccount(
    @Size(min=2, max=5)
    val name: String
)

@RestController
@RequestMapping("/accounts")
class AccountsController {

    @GetMapping("/")
    fun getAll(): Iterable<ViewAccount> =
        listOf(ViewAccount(id=1, name="First"))

    @PostMapping("/")
    fun create(@Valid @RequestBody request: CreateAccount): ViewAccount =
        ViewAccount(id=2, name=request.name)
}

Leave a comment

Your email address will not be published. Required fields are marked *