// REFERENCE

Validation

Installation (Gradle)#

dependencies {
    
    implementation(platform("org.http4k:http4k-bom:6.61.0.0"))

    implementation("org.http4k:http4k-validation")

    // for the JSON body example (any auto-marshalling format module works):
    implementation("org.http4k:http4k-format-jackson")
}

About#

Composable, message-carrying request validation for http4k, built on top of values4k.

values4k supplies the validation primitives: the Validator<T> type, the constraint functions (email(), min(), notBlank(), …) and the combinators (and, or, allOf). http4k-validation wires them into http4k lenses and renders the results as HTTP responses.

Validating lenses#

Attach a Validator to any lens with validated(). A constraint violation throws a LensFailure carrying the Problem. The lens’s own failures do the same: a missing required value becomes Missing, a parse failure becomes Invalid, and an unacceptable content type becomes Unsupported.

Compose validators onto an object’s fields with allOf and the validated infix.

Rendering failures#

Handle every failure with one filter:

val app = ServerFilters.CatchValidationFailure().then(handler)

By default Unsupported maps to 415, everything else to 400, and the response body is the joined messages (ProblemRenderer.Text). Override either:

ServerFilters.CatchValidationFailure(
    statusFor = { if (it.constraint == Constraint.Unsupported) UNSUPPORTED_MEDIA_TYPE else BAD_REQUEST },
    renderer = ProblemRenderer.Rfc9457(Body.auto<ProblemDetails>().toLens(), type = Uri.of("https://api.example.com/problems/validation-error"))
).then(handler)

ProblemRenderer.Rfc9457 renders an RFC 9457 application/problem+json body. The type defaults to about:blank; set it to a URI under your own domain to name the problem type without exposing your stack:

{
  "type": "https://api.example.com/problems/validation-error",
  "title": "Request validation failed",
  "status": 400,
  "instance": "/users",
  "invalidParams": [
    { "name": "Email", "reason": "must be a well-formed email address", "value": "not-an-email" }
  ]
}

Example#

Kotlin example.kt
package content.ecosystem.http4k.reference.validation

import dev.forkhandles.values.allOf
import dev.forkhandles.values.email
import dev.forkhandles.values.min
import dev.forkhandles.values.notBlank
import dev.forkhandles.values.validated
import org.http4k.core.Body
import org.http4k.core.Method.GET
import org.http4k.core.Method.POST
import org.http4k.core.Response
import org.http4k.core.Status.Companion.OK
import org.http4k.core.then
import org.http4k.filter.CatchValidationFailure
import org.http4k.filter.ServerFilters
import org.http4k.format.Jackson.auto
import org.http4k.lens.Path
import org.http4k.lens.Query
import org.http4k.lens.int
import org.http4k.lens.validated
import org.http4k.routing.bind
import org.http4k.routing.routes
import org.http4k.server.SunHttp
import org.http4k.server.asServer

data class CreateUser(val name: String, val email: String, val age: Int)

fun main() {
    val id = Path.int().of("id").validated(min(1))
    val emailQuery = Query.required("email").validated(email())
    val createUser = Body.auto<CreateUser>().toLens().validated(
        allOf(
            CreateUser::name validated notBlank(),
            CreateUser::email validated email(),
            CreateUser::age validated min(18)
        )
    )

    val routes = routes(
        "/users/{id}" bind GET to { request -> Response(OK).body("user ${id(request)}") },
        "/search" bind GET to { request -> Response(OK).body("searching for ${emailQuery(request)}") },
        "/users" bind POST to { request -> Response(OK).body("created ${createUser(request).name}") }
    )

    ServerFilters.CatchValidationFailure()
        .then(routes)
        .asServer(SunHttp(8000))
        .start()
        .block()
}
scarf