Introduction
Controllers and routing
Routes, parameter binding, the raw request and response, object binding, status codes, versioning and prefixes.
@Controller("/users")
class UserController(private val users: UserService) {
@Get fun list(@Query limit: Int?): List<UserDto> = users.all().take(limit ?: 20)
@Get("/{id}") fun get(@Param id: String): UserDto = users.find(id) ?: throw NotFoundException("no such user")
@Post @HttpCode(201) fun create(@Body body: CreateUserDto): UserDto = users.register(body)
@Delete("/{id}") fun remove(@Param id: String) { users.remove(id) } // Unit: 204
}Routes are found by the processor and compiled into a segment trie; path variables are checked against @Param names at build time, and two routes with the same method and path are a build error.
Binding parameters
| Annotation | Reads | Notes |
|---|---|---|
@Param | a path variable | @Param("id") userId: String renames it |
@Query | a query parameter | Int? makes it optional; @Query(defaultValue = "20"); List<T> takes repeated or comma separated values |
@Header, @Cookie | a header, a cookie | |
@Body | the JSON body | decoded by the registered codec |
@Ip | the caller's address | honours X-Forwarded-For |
@FormFile, @FormFiles | multipart uploads | |
Session, Principal | the session, the authenticated caller | by type |
Conversion follows the parameter's type: Int, Long, Double, Boolean, UUID, BigDecimal, Instant, LocalDate, enums. A bad value is a 400 naming the parameter.
A whole object
data class SearchDto(@NotBlank val q: String?, @Min(1) val page: Int = 1, val tags: List<String> = emptyList())
@Get("/search") fun search(@Query dto: SearchDto) = ... // /search?q=boots&page=2&tags=a&tags=b@Query (or @Param) with no name on a data class binds the whole query string, like NestJS @Query() dto, and the validation pipe checks it. The codec reads the strings and converts them; use Jackson for this (kotlinx.serialization does not coerce "2" to an Int).
One property of the body
@Post("/rename") fun rename(@Body("name") name: String, @Body("age") age: Int?) = ...Several @Body("field") parameters are allowed together; a missing non-nullable field is a 400. Only one whole @Body is allowed.
The raw request and response
Most handlers just return a value. When you need the objects themselves, as NestJS's @Req() and @Res() do:
@Get("/export")
fun export(@Request req: HttpRequest, @Response res: RawResponse) {
res.status(200).header("content-disposition", "attachment; filename=users.csv").type("text/csv").send(csv(req.query["q"]))
}@Request gives the HttpRequest (method, path, query, headers, body, attributes). @Response gives a RawResponse with status, header, cookie, type, and one finishing call: send(text|bytes), json(value), stream(ResponseStream), redirect(url) or end(). Once you take it, what the handler returns is ignored, as in Express. If you never send, the answer is empty with the status you set, not a hang.
@Response(passthrough = true) is NestJS's @Res({ passthrough: true }): set status, headers and cookies on the object while Kest still serialises the return value.
@Get("/items") fun items(@Response(passthrough = true) res: RawResponse): List<Item> {
res.status(206).header("content-range", "items 0-9/42")
return page
}Status codes, headers, redirects
@HttpCode, @SetHeader and @Redirect (or returning RedirectTo) work as in NestJS. Return an HttpResponse for complete control. A POST answers 201 by default, a Unit handler 204. Exceptions such as NotFoundException or BadRequestException become the NestJS error shape {statusCode, message, error}.
Sub-domain routing
A controller can serve only requests to a given host, and read parts of the host with @HostParam:
@Controller("/", host = ":tenant.example.com")
class TenantController {
@Get fun home(@HostParam("tenant") tenant: String) = "Welcome, $tenant" // acme.example.com -> "Welcome, acme"
}
@Controller("/", host = "admin.example.com") class AdminController { @Get fun home() = "admin" }
@Controller("/") class PlainController { @Get fun home() = "any other host" }- A
:namelabel matches exactly one label of the host. The port is ignored; matching is case-insensitive. - An exact host (
admin.example.com) wins over a pattern that also matches it. A controller with nohostis the fallback for every other host. - A route whose host does not match is a
404, as if it did not exist. - The same path may be declared on different hosts without a duplicate-route error.
The host comes from the Host header, so behind a proxy make sure it forwards the original host (or the proxy sets X-Forwarded-Host handling yourself in a middleware).
Versioning, prefixes, CORS
app.http(NettyHttpAdapter(8080)) {
setGlobalPrefix("/api", exclude = listOf("/health"))
enableVersioning(Versioning(VersioningType.URI)) // /v1/users; or HEADER, or MEDIA_TYPE
enableCors(CorsOptions(origins = listOf("https://app.example.com"), credentials = true))
useCompression(); useSecurityHeaders()
}Mark controllers or handlers with @Version("2").
Shaping the JSON: @Exclude, @Expose, @Transform
class-transformer for Kest, in json-jackson:
data class UserOut(
val id: String,
@Exclude val password: String, // never in the JSON, in or out
@Expose(name = "full_name") val name: String, // renamed
@Transform(MaskEmail::class) val email: String, // rewritten: "a***@example.com"
@Expose(groups = [AdminGroup::class]) val internalNotes: String, // only for admin responses
)
class MaskEmail : ValueTransformer { override fun transform(value: Any?) = (value as String).let { it.take(1) + "***@" + it.substringAfter('@') } }
@Controller("/users") @UseInterceptors(ClassSerializerInterceptor::class)
class Users {
@Get("/me") fun me() = user // no groups: internalNotes hidden
@SerializeGroups(AdminGroup::class) @Get("/{id}") fun one(@Param id: String) = user // internalNotes shown
}ClassSerializerInterceptor applies it to what a handler returns (use it per controller, or globally with useInterceptors); a property with groups is hidden unless the handler names one of them, and several groups can be named. (Request bodies are read by the codec as usual; @Exclude and @Expose(name) on input are not tested.) Works with the Jackson codec; a String, ByteArray, HttpResponse or stream result passes through untouched.
For server-rendered pages see Views (MVC); to send files and streams see Files, streaming and SSE.