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 🚀

Gradle Setup

First, add the Koin dependency like below:

// Add Jcenter to your repositories if needed
repositories {
    jcenter()    
}
dependencies {
    // Koin for Kotlin apps
    compile 'org.koin:koin-ktor:0.9.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
    install(DefaultHeaders)
    install(CallLogging)

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

    // Routing section
    routing {
        get("/hello") {
            call.respondText(service.sayHello())
        }
    }
}

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.KoinApplicationKt.main ]
    }
}

Declare your dependencies

Let’s assemble our components with a Koin module:

val helloAppModule = applicationContext {
    bean { HelloServiceImpl(get()) as HelloService } // get() Will resolve HelloRepository
    bean { HelloRepository() }
}

Start and Inject

Finally, let’s start Koin and Ktor:

fun main(args: Array<String>) {
    // Start Koin
    startKoin(listOf(helloAppModule))
    // 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:

General Topics

Developer Guide

Soon…