Getting started with Ktor

Let’s start with a Ktor web application & Koin


Ktor is a framework for building asynchronous servers and clients in connected systems using the powerful Kotlin programming language. We will use Ktor here, to build a simple web application.

Let’s go with the following components to chain : a Controller, a Service and a Repository.

Ktor Controller (http) -> Service (business) -> Repository (data)
  • a Ktor Controller (routing function) to handle http route and return result from the service
  • a Service to handle business and take data from repository
  • a Repository to provide data

All sources are available in the Koin’s github repository

Let’s go 🚀

Get the code

Checkout the project directly on Github or download the zip file

Gradle Setup

First, add the Koin dependency like below:

// Add Jcenter to your repositories if needed
repositories {
dependencies {
    // Koin for Kotlin apps
    compile 'org.koin:koin-ktor:1.0.2'

Service & Repository

Let’s write our Service, a component that will ask Repository for data:

interface HelloService {
    fun sayHello(): String

class HelloServiceImpl(val helloRepository: HelloRepository) : HelloService {
    override fun sayHello() = "Hello ${helloRepository.getHello()} !"

and our Repository, which provide data:

class HelloRepository {
    override fun getHello(): String = "Ktor & Koin"

HTTP Controller

Finally, we need an HTTP Controller to create the HTTP Route. In Ktor is will be expressed through an Ktor extension function:

fun Application.main() {
    // Install Ktor features

    // Lazy inject HelloService
    val service: HelloService by inject()

    // Routing section
    routing {
        get("/hello") {

Check that your application.conf is configured like below, to help start the Application.main function:

ktor {
    deployment {
        port = 8080

        // For dev purpose
        //autoreload = true
        //watch = [org.koin.sample]

    application {
        modules = [ org.koin.sample.HelloApplicationKt.main ]

Declare your dependencies

Let’s assemble our components with a Koin module:

val helloAppModule = module {
    single<HelloService> { HelloServiceImpl(get()) } // get() Will resolve HelloRepository
    single { HelloRepository() }

Start and Inject

Finally, let’s start Koin and Ktor:

fun main(args: Array<String>) {
    // Start Koin
    // Start Ktor
    embeddedServer(Netty, commandLineEnvironment(args)).start()

That’s it! You’re ready to go. Chech the http://localhost:8080/hello url!

What’s Next?

You have finished this starting tutorial. Below are some topics for further reading:

Also other getting started project: