- Setting up a Gradle Build
- Basic Kotlin build.gradle file (without Ktor)
- Add Ktor dependencies and configure build settings
- Choose your engine and configure it
- Final build.gradle (with Ktor)
- IntelliJ: Prerequisites
- IntelliJ: Start a Project
- IntelliJ: Gradle Setup
- IntelliJ: Create the App
- IntelliJ: Improve the app with the Application object
- IntelliJ: Extract out Configuration Data
- Configure logging
Setting up a Gradle Build
In this guide, we will show you how to create a build.gradle fileand how to configure it to support Ktor.
Table of contents:
- Basic Kotlin
build.gradlefile (without Ktor) - Add Ktor dependencies and configure build settings
- Choose your engine and configure it
- Final
build.gradle(with Ktor) - IntelliJ: Prerequisites
- IntelliJ: Start a Project
- IntelliJ: Gradle Setup
- IntelliJ: Create the App
- IntelliJ: Improve the app with the Application object
- IntelliJ: Extract out Configuration Data
- Configure logging
Basic Kotlin build.gradle file (without Ktor)
First of all, you need a skeleton build.gradle file including Kotlin.You can create it with any text editor, or you can use IntelliJ to createit following the IntelliJ guide.
The initial file looks like this:
build.gradle
1. group 'Example'
2. version '1.0-SNAPSHOT'
4. buildscript {
5. ext.kotlin_version = '1.3.61'
7. repositories {
8. mavenCentral()
9. }
10. dependencies {
11. classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
12. }
13. }
15. apply plugin: 'java'
16. apply plugin: 'kotlin'
18. sourceCompatibility = 1.8
20. repositories {
21. jcenter()
22. }
24. dependencies {
25. compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version"
26. testCompile group: 'junit', name: 'junit', version: '4.12'
27. }
Add Ktor dependencies and configure build settings
Ktor artifacts are located in a specific repository on bintray.And its core has dependencies on the kotlinx.coroutines library thatcan be found on jcenter.
You have to add both to the repositories block in the build.gradle file:
1. jcenter()
You have to specify that version in each Ktor artifact reference,and to avoid repetitions, you can specify that version in an extra propertyin the buildscript block (or in a gradle.properties file) for using it later:
1. ext.ktor_version = '1.3.0'
Now you have to add the ktor-server-core artifact, referencing the ktor_version you specified:
1. compile "io.ktor:ktor-server-core:$ktor_version"
In groovy, there are single-quoted strings (instead of characters)and double-quoted strings, to be able to interpolate variables likeversions, you have to use double-quoted strings.
You need to tell the Kotlin compiler to generate bytecode compatible with Java 8:
1. compileKotlin {
2. kotlinOptions.jvmTarget = "1.8"
3. }
4. compileTestKotlin {
5. kotlinOptions.jvmTarget = "1.8"
6. }
Choose your engine and configure it
Ktor can run in many environments, such as Netty, Jetty or any otherServlet-compatible Application Container such as Tomcat.
This example shows you how to configure Ktor with Netty.For other engines see artifacts for a list ofavailable artifacts.
You will add a dependency for ktor-server-netty using thektor_version property you have created. This module providesa Netty web server and all the required code to run Ktorapplication on top of it:
1. compile "io.ktor:ktor-server-netty:$ktor_version"
Final build.gradle (with Ktor)
When you are done, the build.gradle file should look like this:
build.gradle
1. group 'Example'
2. version '1.0-SNAPSHOT'
4. buildscript {
5. ext.kotlin_version = '1.3.61'
6. ext.ktor_version = '1.3.0'
8. repositories {
9. mavenCentral()
10. }
11. dependencies {
12. classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
13. }
14. }
16. apply plugin: 'java'
17. apply plugin: 'kotlin'
19. sourceCompatibility = 1.8
20. compileKotlin {
21. kotlinOptions.jvmTarget = "1.8"
22. }
23. compileTestKotlin {
24. kotlinOptions.jvmTarget = "1.8"
25. }
27. kotlin {
28. experimental {
29. coroutines "enable"
30. }
31. }
33. repositories {
34. jcenter()
35. }
37. dependencies {
38. compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version"
39. compile "io.ktor:ktor-server-netty:$ktor_version"
40. testCompile group: 'junit', name: 'junit', version: '4.12'
41. }
You can now run Gradle (just gradle or ./gradlew if using the wrapper)to fetch dependencies and verify everything is set up correctly.
This tutorial will guide you from the most basic setup through to a fullfeatured setup you can use to start developing your app.
IntelliJ: Prerequisites
- The most recent version of IntelliJ IDEA
-
Kotlin and Gradle plugins enabled (They should be enabled by default.) You can check this in IntelliJ IDEA in the main menu:
-
Windows:
File -> Settings -> Plugins - Mac:
IntelliJ IDEA -> Settings -> Plugins
IntelliJ: Start a Project
File -> New -> Project:

- Select Gradle and under Additional Libraries and Frameworks, check Java and Kotlin (Java). Confirm that Project SDK is completed and click
Next:

- Enter a GroupId:
Exampleand ArtifactId:Exampleand click Next:

- Complete Project name:
Exampleand Project location:a/path/on/your/filesystemand clickFinish:

- Wait a few seconds for Gradle to run, and you should see a project structure like the following (with a few other files and directories):

-
Update your
build.gradlefile with the artifact and repositories for the classes to be available: -
Include
compile("io.ktor:ktor-server-netty:$ktor_version"), in yourbuild.gradle’sdependenciesblock - Include
jcenter()in yourrepositoriesblock
For a more detailed guide on setting up the build.gradle file, check the Getting Started with Gradle section.
When auto-import options, shows up (likely on bottom right hand side) click allow auto-import.
IntelliJ: Gradle Setup
This section assumes you have some basic knowledge of Gradle. If you have never used Gradle,gradle.org provides several guides to help you get started.
You can set-up a simple Ktor application using Gradle like this:

Text version:
Groovy
1. // build.gradle
3. group 'Example'
4. version '1.0-SNAPSHOT'
6. buildscript {
7. ext.kotlin_version = '1.3.61'
8. ext.ktor_version = '1.3.0'
10. repositories {
11. mavenCentral()
12. }
13. dependencies {
14. classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
15. }
16. }
18. apply plugin: 'java'
19. apply plugin: 'kotlin'
20. apply plugin: 'application'
22. mainClassName = 'MainKt'
24. sourceCompatibility = 1.8
25. compileKotlin { kotlinOptions.jvmTarget = "1.8" }
26. compileTestKotlin { kotlinOptions.jvmTarget = "1.8" }
28. repositories {
29. mavenCentral()
30. }
32. dependencies {
33. compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version"
34. compile "io.ktor:ktor-server-netty:$ktor_version"
35. compile "ch.qos.logback:logback-classic:1.2.3"
36. testCompile group: 'junit', name: 'junit', version: '4.12'
37. }
Kotlin
1. // build.gradle.kts
3. import org.jetbrains.kotlin.gradle.dsl.Coroutines
4. import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
6. group = "Example"
7. version = "1.0-SNAPSHOT"
9. val ktor_version = "1.3.0"
11. plugins {
12. application
13. kotlin("jvm") version "1.3.61"
14. }
16. repositories {
17. mavenCentral()
18. }
20. java {
21. sourceCompatibility = JavaVersion.VERSION_1_8
22. }
24. tasks.withType<KotlinCompile>().all {
25. kotlinOptions.jvmTarget = "1.8"
26. }
28. application {
29. mainClassName = "MainKt"
30. }
32. dependencies {
33. compile(kotlin("stdlib-jdk8"))
34. compile("io.ktor:ktor-server-netty:$ktor_version")
35. compile("ch.qos.logback:logback-classic:1.2.3")
36. testCompile(group = "junit", name = "junit", version = "4.12")
37. }
Since Ktor is not yet 1.0, we have custom Maven repositories for distributing our early preview artifacts.You have to set up a couple of repositories as shown below, so your tools can find Ktor artifacts and dependencies.
Of course, don’t forget to include the actual artifact! For our quickstart, we are using the ktor-server-netty artifact.That includes Ktor’s core, netty, and the ktor-netty connector as transitive dependencies.You can, of course, include any additional dependencies that you need.
Since Ktor is designed to be modular, you will require additional artifacts and potentially other repositoriesfor specific features. You can find the required artifacts (and repositories where required) for each feature in thespecific feature documentation.
IntelliJ: Create the App
Select the src/main/kotlin directory and create a new package. We will call it blog.
Select that directory and create a new kotlin file under it named BlogApp


Copy and paste in the most basic setup for an app so that it looks like:
BlogApp.kt
1. package blog
3. import io.ktor.application.*
4. import io.ktor.http.*
5. import io.ktor.response.*
6. import io.ktor.routing.*
7. import io.ktor.server.engine.*
8. import io.ktor.server.netty.*
10. fun main(args: Array<String>) {
11. embeddedServer(Netty, 8080) {
12. routing {
13. get("/") {
14. call.respondText("My Example Blog", ContentType.Text.Html)
15. }
16. }
17. }.start(wait = true)
18. }

Now you can Run ‘blog.BlogAppKt’. You can do it, by pressing the glutter icon with the 🐞 symbol and selecting Debug 'blog.BlogAppKt':

This will also create a run configuration in the upper-right part of IntelliJ, that will allow runningthis configuration again easily:

This will start the Netty web server.In your browser enter the URL: localhost:8080And you should see your example blog page.

IntelliJ: Improve the app with the Application object
The setup above has a lot of nested blocks and is not ideal for starting to add functionality to your app. We can improve it by using the Application object and referring to that from an embeddedServer call in the main function.
Change your code in BlogApp.kt to the following to try this:
BlogApp.kt
1. package blog
3. import io.ktor.application.*
4. import io.ktor.features.*
5. import io.ktor.http.*
6. import io.ktor.response.*
7. import io.ktor.routing.*
8. import io.ktor.server.engine.*
9. import io.ktor.server.netty.*
11. fun Application.module() {
12. install(DefaultHeaders)
13. install(CallLogging)
14. install(Routing) {
15. get("/") {
16. call.respondText("My Example Blog2", ContentType.Text.Html)
17. }
18. }
19. }
21. fun main(args: Array<String>) {
22. embeddedServer(Netty, 8080, watchPaths = listOf("BlogAppKt"), module = Application::module).start()
23. }
IntelliJ: Extract out Configuration Data
Although we can designate some application configuration data in the main function embeddedServer call, we can provide more flexibility for future deployments and changes by extracting this out to a separate configuration file. In the src/main/resources directory we will create a new text file named application.conf with the following content:
application.conf
1. ktor {
2. deployment {
3. port = 8080
4. }
6. application {
7. modules = [ blog.BlogAppKt.main ]
8. }
9. }
Then we delete the main function from BlogApp.kt and change fun Application.module() to fun Application.main(). However, if we run the application now, it will fail with an error message like “Top-level function ‘main’ not found in package blog.” Our Application.main() function is now a function extension and does not qualify as a top-level main function.
This requires us to indicate a new main class as IntelliJ IDEA will no longer be able to find it automatically. In build.gradle we add:
Groovy
1. // build.gradle
3. apply plugin: 'application'
5. //mainClassName = 'io.ktor.server.netty.DevelopmentEngine' // For versions < 1.0.0-beta-3
6. mainClassName = 'io.ktor.server.netty.EngineMain' // Starting with 1.0.0-beta-3
Kotlin
1. // build.gradle.kts
3. plugins {
4. application
5. // ...
6. }
8. application {
9. mainClassName = "io.ktor.server.netty.EngineMain"
10. }
And then go to Run -> Edit Configurations select the blog.BlogAppKt configuration and change its Main class to:io.ktor.server.netty.EngineMain
Now when we run the new configuration, the application will start again.
Configure logging
If you want to log application events and useful information,you can read about it further in the logging page.
