Map Ktor validation failures to JSON 400 responses
When request-value validation fails, RequestValidation throws RequestValidationException. StatusPages can map it to HTTP 400 with a consistent JSON error body. This guide uses Ktor 3.6.1, Kotlin serialization and POST /customers; docs checked 2026-11-20.
When request-value validation fails, RequestValidation throws RequestValidationException. StatusPages can map it to HTTP 400 with a consistent JSON error body. This guide uses Ktor 3.6.1, Kotlin serialization and POST /customers; docs checked 2026-11-20.
Flow and prerequisites
ContentNegotiation decodes JSON and serializes responses; RequestValidation checks decoded values; StatusPages maps the exception to a public error contract. Require a positive id and return a stable code with a safe message. Keep internal exceptions, traces and request bodies private. Install plugins before routes; testApplication needs ktor-server-test-host and kotlin-test and opens no real port. Invalid input should return JSON 400; valid input 201.
implementation(ktorLibs.server.contentNegotiation)
implementation(ktorLibs.serialization.kotlinx.json)
implementation(ktorLibs.server.requestValidation)
implementation(ktorLibs.server.statusPages)
testImplementation(ktorLibs.server.testHost)
testImplementation(kotlin("test"))JSON contract and plugins
import kotlinx.serialization.Serializable
@Serializable
data class Customer(val id: Int, val name: String)
@Serializable
data class ApiError(val code: String, val message: String)import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.plugins.requestvalidation.*
import io.ktor.server.plugins.statuspages.*
import io.ktor.server.plugins.contentnegotiation.*
import io.ktor.serialization.kotlinx.json.*
import io.ktor.server.request.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
fun Application.module() {
install(ContentNegotiation) { json() }
install(RequestValidation) {
validate<Customer> { customer ->
if (customer.id <= 0) {
ValidationResult.Invalid("id must be positive")
} else {
ValidationResult.Valid
}
}
}
install(StatusPages) {
exception<RequestValidationException> { call, _ ->
call.respond(
HttpStatusCode.BadRequest,
ApiError("invalid_request", "Customer id must be positive.")
)
}
status(HttpStatusCode.NotFound) { call, _ ->
call.respond(
HttpStatusCode.NotFound,
ApiError("not_found", "Resource not found.")
)
}
}
routing {
post("/customers") {
val customer = call.receive<Customer>()
call.respond(HttpStatusCode.Created, customer)
}
}
}Testing status and body
import io.ktor.client.request.*
import io.ktor.client.statement.*
import io.ktor.http.*
import io.ktor.server.testing.*
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive
import kotlin.test.Test
import kotlin.test.assertEquals
class CustomerRouteTest {
@Test
fun invalidIdReturnsJson400() = testApplication {
application { module() }
val response = client.post("/customers") {
contentType(ContentType.Application.Json)
accept(ContentType.Application.Json)
setBody("""{"id":0,"name":"Mina"}""")
}
assertEquals(HttpStatusCode.BadRequest, response.status)
val body = Json.parseToJsonElement(response.bodyAsText()).jsonObject
assertEquals("invalid_request", body["code"]?.jsonPrimitive?.content)
}
@Test
fun validCustomerReturnsCreated() = testApplication {
application { module() }
val response = client.post("/customers") {
contentType(ContentType.Application.Json)
accept(ContentType.Application.Json)
setBody("""{"id":7,"name":"Mina"}""")
}
assertEquals(HttpStatusCode.Created, response.status)
}
}.\gradlew.bat testTroubleshooting
Run the Gradle Wrapper on Windows; both tests should pass. For 415 check Content-Type, for 406 Accept. Validation and deserialization are different stages. Confirm StatusPages is installed in the tested module. Recheck docs after changing versions or serializers.
Official references
[Status pages](https://ktor.io/docs/server-status-pages.html)
[Request validation](https://ktor.io/docs/server-request-validation.html)
[Content negotiation and serialization](https://ktor.io/docs/server-serialization.html)
[Testing in Ktor Server](https://ktor.io/docs/server-testing.html)