Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 38 ยท Plugins and Serialization

Request Validation

Validate incoming data in Ktor with the RequestValidation plugin: validate blocks, ValidationResult, handling RequestValidationException, and designing helpful error output.

Deserialising JSON proves only that the shape is right: a title exists and is a string. It does not prove the data is acceptable: an empty title, a negative price, a year in the year 3000, an email without an @. Validating that is your responsibility, and doing it consistently is the difference between an API that gives clear errors and one that stores garbage. This lesson shows Ktor's RequestValidation plugin and a hand-rolled approach, then lets you run a validator in a stand-in.

The RequestValidation plugin

Dependency: ktor-server-request-validation. You declare rules per class; Ktor runs them inside call.receive<T>():

Kotlin
import io.ktor.server.plugins.requestvalidation.*

@Serializable
data class NewBook(val title: String, val author: String, val year: Int? = null, val price: Double)

fun Application.module() {
    install(ContentNegotiation) { json() }
    install(RequestValidation) {
        validate<NewBook> { book ->
            when {
                book.title.isBlank() -> ValidationResult.Invalid("title must not be blank")
                book.title.length > 200 -> ValidationResult.Invalid("title is longer than 200 characters")
                book.price < 0 -> ValidationResult.Invalid("price must not be negative")
                book.year != null && book.year !in 1450..2100 -> ValidationResult.Invalid("year is out of range")
                else -> ValidationResult.Valid
            }
        }
    }
    install(StatusPages) {
        exception<RequestValidationException> { call, cause ->
            call.respond(
                HttpStatusCode.UnprocessableEntity,
                mapOf("error" to "validation_failed", "reasons" to cause.reasons.joinToString("; "))
            )
        }
    }
    routing {
        post("/books") {
            val book = call.receive<NewBook>()     // validation runs here, before your code continues
            call.respond(HttpStatusCode.Created, book)
        }
    }
}

When a rule returns ValidationResult.Invalid(reason), receive throws RequestValidationException, which carries reasons (a list of strings). Without a StatusPages handler Ktor answers 400 with a text body listing the reasons. With one, you control the format. ValidationResult.Invalid also accepts a list of reasons, so you can report several problems at once rather than one per round trip:

Kotlin
validate<NewBook> { book ->
    val problems = buildList {
        if (book.title.isBlank()) add("title must not be blank")
        if (book.price < 0) add("price must not be negative")
    }
    if (problems.isEmpty()) ValidationResult.Valid else ValidationResult.Invalid(problems)
}

Validation in the domain layer

The plugin is convenient for shape-level rules. Rules that need data, "email already registered", "stock is too low", belong in your service layer, where they can query the database, and are reported with a domain exception (Conflict, ValidationFailed) that StatusPages translates (see Status Pages). A practical split:

Rule Where
Not blank, length, range, format RequestValidation
Email unique, foreign key exists Service layer + exception
Who may do it Authorization (authentication chapter)

Kotlin's own require(condition) { "message" } is handy inside init { } blocks of value classes and throws IllegalArgumentException, which you can map to 400.

What a good validation error looks like

  • Say which field and what is wrong: "price": "must not be negative".
  • Report all problems in one response.
  • Use a stable machine-readable code next to the human message, so clients can translate it.
  • Return 400 (or 422) with a JSON body, never a stack trace.

Stand-in: a validator that reports every problem

The stand-in defines a small validation DSL (rule(field) { ... }) in plain Kotlin and checks several inputs, collecting errors per field. It mirrors ValidationResult.Valid / Invalid.

Kotlin Stand-in: collecting validation problems

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Input #3 shows the value of reporting everything: a client fixes all four mistakes in one round trip.

Sanitise, do not just validate

Validation says "no". Sometimes you also want to normalise before storing: trim() titles, lowercase emails, strip control characters. Do this after validation and before saving, in one place, so the database never contains " [email protected] " and "[email protected]" as two users.

Validate on the server even when your front end validates too. Front-end checks are for convenience; anyone can send requests directly to your API.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does receive<T>() do when a validate<T> rule returns Invalid?

    The exception carries the reasons and can be mapped with StatusPages.
  2. 2. Which rule belongs in the service layer rather than in RequestValidation?

    Rules that need data from the database belong in the service layer.
  3. 3. Why report all problems at once?

    The client can fix everything before retrying.
  4. 4. Is front-end validation enough?

    Server-side validation is mandatory; client-side checks are only a convenience.

Summary

  • Deserialisation checks shape; validation checks meaning.
  • install(RequestValidation) { validate<T> { ... } } runs rules inside receive; failures throw RequestValidationException.
  • Map the exception to a clear 400/422 JSON error with all reasons.
  • Data-dependent rules belong in the service layer.
  • Normalise after validating.

Next: Logging, CORS and Compression