Kest

Search

Search the documentation

Introduction

First steps

Build and run your first Kest application, and understand every piece of it.

What is Kest?

Kest is a framework for building backend applications on the JVM, in Kotlin (and Java). You write your application as small classes (controllers that answer HTTP requests, services that hold the logic, repositories that talk to a database), and Kest connects them together. It will feel familiar if you have used NestJS, Spring or ASP.NET, and you do not need to know any of them.

Two ideas are worth knowing before you start:

  1. Dependency injection. A class says what it needs in its constructor (class OrderController(private val orders: OrderService)) and Kest hands it one. You never write OrderService() yourself, so every class is easy to test and to replace.
  2. Wiring happens at build time. A tool called the processor (KSP) reads your code while it compiles and generates the connecting code. There is no scanning at start-up and no reflection magic, so the application starts fast and wiring mistakes fail the build, not production.
Loading diagram…

The quickest way

kest new shop --package com.acme.shop
cd shop && gradle wrapper && ./gradlew run
./gradlew kest --args="g resource orders"      # add a CRUD resource, wired in

kest new writes a ready project: a Gradle build, an application module, a first controller, configuration and a test. See The command line. The rest of this page builds the same thing by hand, so you can see what each piece does.

Requirements

  • JDK 21 as JAVA_HOME (java -version should say 21). A different default JDK is the most common reason a first build fails.
  • Gradle with the Kotlin plugin and the com.google.devtools.ksp plugin (the project that kest new writes has both).

Dependencies

build.gradle.kts
plugins { id("com.google.devtools.ksp") }
 
dependencies {
    implementation(platform("io.kest.framework:bom:<version>"))   // one version for every package
    implementation("io.kest.framework:core")
    implementation("io.kest.framework:http-server")
    implementation("io.kest.framework:http-server-netty")         // the web server engine (or http-server-jdk)
    implementation("io.kest.framework:json-kotlinx")              // turns JSON into objects and back (or json-jackson)
    implementation("io.kest.framework:validation")
    ksp(platform("io.kest.framework:bom:<version>"))        // the BOM must be applied to ksp too
    ksp("io.kest.framework:processor")                            // once; it serves every package
}

Kest is split into packages (core, http-server, orm, queue...). You add only what you use. The BOM (bill of materials) pins one version for all of them so they always fit together, and the processor is added once and works for every package.

A first application

Three kinds of class make up most applications.

A service holds the logic. @Injectable tells Kest it may create one and give it to anyone who asks:

UsersModule.kt
data class CreateUserDto(@field:Email val email: String)       // what a client sends
data class UserDto(val id: String, val email: String)         // what we answer
 
@Injectable
class UserService {
    private val users = HashMap<String, UserDto>()
    fun find(id: String) = users[id]
    fun register(dto: CreateUserDto) = UserDto(dto.email.substringBefore('@'), dto.email).also { users[it.id] = it }
}

A controller receives HTTP requests. Each method is a route: the annotation says the HTTP method and path, and the parameters say where each value comes from:

@Controller("/users")                                   // every route below starts with /users
class UserController(private val users: UserService) { // Kest passes the service in
    @Post fun create(@Body body: CreateUserDto): UserDto = users.register(body)      // POST /users, JSON body -> object
 
    @Get("/{id}")                                       // GET /users/42
    fun get(@Param id: String): UserDto =
        users.find(id) ?: throw NotFoundException("user $id not found")                // becomes a 404 response
 
    @Get fun list(@Query limit: Int?): List<UserDto> = emptyList()                      // GET /users?limit=10 (optional)
}

A module groups related classes and says what belongs together:

@Module(providers = [UserService::class], controllers = [UserController::class])
class UsersModule

Finally an application module that imports the others, and a main that starts everything:

Main.kt
@Module(imports = [UsersModule::class, KotlinxJsonModule::class, ValidationModule::class])
class AppModule
 
fun main(args: Array<String>) {
    val app = Kest.run<AppModule>(args)                  // build the container: create every provider, in the right order
    app.http(NettyHttpAdapter(port = 8080)) {            // start the web server
        usePipes(ValidationPipe::class)                  // check every request body against its annotations
    }
    Thread.currentThread().join()                        // keep the process alive
}

Run it and try it

./gradlew run

The log lists every route it found, then says the server is up:

[RouterExplorer] Mapped {/users, POST} route
[RouterExplorer] Mapped {/users/{id}, GET} route
curl -X POST localhost:8080/users -H 'content-type: application/json' -d '{"email":"ann@example.com"}'
# {"id":"ann","email":"ann@example.com"}
 
curl localhost:8080/users/ann        # {"id":"ann","email":"ann@example.com"}
curl localhost:8080/users/nobody     # {"statusCode":404,"message":"user nobody not found","error":"Not Found"}

A request with a bad body is refused before your code runs, with a clear message:

curl -X POST localhost:8080/users -H 'content-type: application/json' -d '{"email":"nope"}'
# {"statusCode":400,"message":["email must be an email"],"error":"Bad Request"}

What happened when you pressed run

Loading diagram…

The mistakes everyone makes once

You seeIt meansFix
the build fails: 'X' is listed in 'controllers' but is not annotated with @Injectable, @Controller or @Repositorya class is in a module list but Kest does not know what it isadd the annotation
the build fails: X needs Y, but it is not visible in ...a class asks for something its module cannot seethe message names the fix: add Y to a module's providers, or import the module that exports it
No provider registered for ...Y at starta package you use is configured at start-up (a database, a secret) and you did not import its moduleKest.run<AppModule> { import(TheModule.forRoot { ... }) }
No JSON codec registeredno JSON module importedimport KotlinxJsonModule or JacksonJsonModule
Gradle or KSP errors right awaythe wrong JDKJAVA_HOME must be JDK 21

Where next

Read more