Gradle

note

This help topic is in development and will be updated in the future.

In this guide, we will show you how to create a build.gradle file and how to configure it to support Ktor.

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 create it following the IntelliJ guide.

The initial file looks like this:

  1. group 'Example'
  2. version '1.0-SNAPSHOT'
  3. buildscript {
  4. ext.kotlin_version = '%kotlin_version%'
  5. repositories {
  6. mavenCentral()
  7. }
  8. dependencies {
  9. classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
  10. }
  11. }
  12. apply plugin: 'java'
  13. apply plugin: 'kotlin'
  14. sourceCompatibility = 1.8
  15. repositories {
  16. jcenter()
  17. }
  18. dependencies {
  19. compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version"
  20. testCompile group: 'junit', name: 'junit', version: '4.12'
  21. }

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 that can 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 property in the buildscript block (or in a gradle.properties file) for using it later:

  1. ext.ktor_version = '1.5.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"

note

In groovy, there are single-quoted strings (instead of characters) and double-quoted strings, to be able to interpolate variables like versions, 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 other Servlet-compatible Application Container such as Tomcat.

This example shows you how to configure Ktor with Netty. For other engines, see Add Dependencies for a list of available artifacts.

You will add a dependency for ktor-server-netty using the ktor_version property you have created. This module provides a Netty web server and all the required code to run Ktor application 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:

  1. group 'Example'
  2. version '1.0-SNAPSHOT'
  3. buildscript {
  4. ext.kotlin_version = '%kotlin_version%'
  5. ext.ktor_version = '1.5.0'
  6. repositories {
  7. mavenCentral()
  8. }
  9. dependencies {
  10. classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
  11. }
  12. }
  13. apply plugin: 'java'
  14. apply plugin: 'kotlin'
  15. sourceCompatibility = 1.8
  16. compileKotlin {
  17. kotlinOptions.jvmTarget = "1.8"
  18. }
  19. compileTestKotlin {
  20. kotlinOptions.jvmTarget = "1.8"
  21. }
  22. kotlin {
  23. experimental {
  24. coroutines "enable"
  25. }
  26. }
  27. repositories {
  28. jcenter()
  29. }
  30. dependencies {
  31. compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version"
  32. compile "io.ktor:ktor-server-netty:$ktor_version"
  33. testCompile group: 'junit', name: 'junit', version: '4.12'
  34. }

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 full featured setup you can use to start developing your app.

IntelliJ: Prerequisites

  1. The most recent version of IntelliJ IDEA

  2. 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

  1. File -> New -> Project:

    Ktor IntelliJ: File New Project

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

    Ktor IntelliJ: Gradle Kotlin JVM

  3. Enter a GroupId: Example and ArtifactId: Example and click Next:

    Ktor IntelliJ: GroupId

  4. Complete Project name: Example and Project location: a/path/on/your/filesystem and click Finish:

    Ktor IntelliJ: Project Location Name

  5. 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):

    Ktor IntelliJ: Project Structure

  6. Update your build.gradle file with the artifact and repositories for the classes to be available:

    • Include compile("io.ktor:ktor-server-netty:$ktor_version"), in your build.gradle‘s dependencies block

    • Include jcenter() in your repositories block

    Ktor IntelliJ: Build Gradle

note

Gradle - 图7

When auto-import options, shows up (likely at the bottom right-hand side) click allow auto-import.

IntelliJ: Gradle Setup

note

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:

Ktor Build with Gradle

  1. // build.gradle.kts
  2. import org.jetbrains.kotlin.gradle.dsl.Coroutines
  3. import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
  4. group = "Example"
  5. version = "1.0-SNAPSHOT"
  6. val ktor_version = "1.5.0"
  7. plugins {
  8. application
  9. kotlin("jvm") version "%kotlin_version%"
  10. }
  11. repositories {
  12. mavenCentral()
  13. }
  14. java {
  15. sourceCompatibility = JavaVersion.VERSION_1_8
  16. }
  17. tasks.withType<KotlinCompile>().all {
  18. kotlinOptions.jvmTarget = "1.8"
  19. }
  20. application {
  21. mainClassName = "MainKt"
  22. }
  23. dependencies {
  24. compile(kotlin("stdlib-jdk8"))
  25. compile("io.ktor:ktor-server-netty:$ktor_version")
  26. compile("ch.qos.logback:logback-classic:1.2.3")
  27. testCompile(group = "junit", name = "junit", version = "4.12")
  28. }
  1. // build.gradle
  2. group 'Example'
  3. version '1.0-SNAPSHOT'
  4. buildscript {
  5. ext.kotlin_version = '%kotlin_version%'
  6. ext.ktor_version = '1.5.0'
  7. repositories {
  8. mavenCentral()
  9. }
  10. dependencies {
  11. classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
  12. }
  13. }
  14. apply plugin: 'java'
  15. apply plugin: 'kotlin'
  16. apply plugin: 'application'
  17. mainClassName = 'MainKt'
  18. sourceCompatibility = 1.8
  19. compileKotlin { kotlinOptions.jvmTarget = "1.8" }
  20. compileTestKotlin { kotlinOptions.jvmTarget = "1.8" }
  21. repositories {
  22. mavenCentral()
  23. }
  24. dependencies {
  25. compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version"
  26. compile "io.ktor:ktor-server-netty:$ktor_version"
  27. compile "ch.qos.logback:logback-classic:1.2.3"
  28. testCompile group: 'junit', name: 'junit', version: '4.12'
  29. }

Text version:

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 repositories for specific features. You can find the required artifacts (and repositories where required) for each feature in the specific 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

Ktor IntelliJ: Create Kotlin File

Ktor IntelliJ: Create Kotlin File Name

Copy and paste in the most basic setup for an app so that it looks like:

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

Ktor IntelliJ: Program

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

Ktor IntelliJ: Program Run

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

Ktor IntelliJ: Program Run Config

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

Ktor IntelliJ: Website

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:

  1. package blog
  2. import io.ktor.application.*
  3. import io.ktor.features.*
  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.*
  9. fun Application.module() {
  10. install(DefaultHeaders)
  11. install(CallLogging)
  12. install(Routing) {
  13. get("/") {
  14. call.respondText("My Example Blog2", ContentType.Text.Html)
  15. }
  16. }
  17. }
  18. fun main(args: Array<String>) {
  19. embeddedServer(Netty, 8080, watchPaths = listOf("BlogAppKt"), module = Application::module).start()
  20. }

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:

  1. ktor {
  2. deployment {
  3. port = 8080
  4. }
  5. application {
  6. modules = [ blog.BlogAppKt.main ]
  7. }
  8. }

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:

  1. // build.gradle
  2. apply plugin: 'application'
  3. //mainClassName = 'io.ktor.server.netty.DevelopmentEngine' // For versions < 1.0.0-beta-3
  4. mainClassName = 'io.ktor.server.netty.EngineMain' // Starting with 1.0.0-beta-3
  1. // build.gradle.kts
  2. plugins {
  3. application
  4. // ...
  5. }
  6. application {
  7. mainClassName = "io.ktor.server.netty.EngineMain"
  8. }

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.