Creating Your First Application

In this tutorial you will learn how to create a simple self-hosted Ktor server application that responds to HTTP requests with Hello, World!.Ktor applications can be built using common build systems such as Maven or Gradle.

Table of contents:

Including the right dependencies

Ktor is split up into several groups of artifacts,allowing you to include only the functionality that you will need. And thus reducing the size of a fat-jar containing all the code, and the startup time.

In this case, you only need to include the artifact ktor-server-netty.For a list of all the artifacts available, please check the Artifacts page.

Release versions of these dependencies are available at jcenter and maven central.For pre-releases we host them on Bintray kotlin/ktor.

For a more detailed guide on setting up build files with different build systems check:

Creating a self-hosted Application

Ktor allows applications to run within an Application Server compatible with Servlets, such as Tomcat,or as an embedded application, using Jetty, Netty or CIO.

In this tutorial, we are going to create a self-hosted application using Netty.

You can start by calling the embeddedServer function, passing in the engine factory as the first argument,the port as the second argument and the actual application code as the fourth argument (third argumentis the host which is 0.0.0.0 by default).

The code below defines a single route that responds to the GET verb on the URL / withthe text Hello, world!

After defining the routes, you have to start the server by calling the server.start method,passing as argument a boolean to indicate whether you want the main thread of the application to block.

Main.kt

  1. import io.ktor.application.*
  2. import io.ktor.http.*
  3. import io.ktor.response.*
  4. import io.ktor.routing.*
  5. import io.ktor.server.engine.*
  6. import io.ktor.server.netty.*
  7. fun main(args: Array<String>) {
  8. val server = embeddedServer(Netty, 8080) {
  9. routing {
  10. get("/") {
  11. call.respondText("Hello, world!", ContentType.Text.Html)
  12. }
  13. }
  14. }
  15. server.start(wait = true)
  16. }

If your server is just listening for HTTP requests and do not want to do anything else after that in the setup,you will normally call the server.start with wait = true.

Running the Application

Given that the entry point of your application is the standard Kotlin main function, you can simply run it, effectively starting the server and listening on the specified port.

Checking the localhost:8080 page in your browser, you should see the Hello, world! text.

Next Steps

This was the simplest example of getting a self-hosted Ktor application up and running. A recommended tour to continue learning Ktor on the server would be: