KMPizza
Kotlin Multiplatform + Pizza = ❤️

Step 4: Build and test Ktor application with shadowJar

By now you must be very excited to try it out. At least I am. Teaching yourself software development always leaves room for surprise. What if it doesn’t work? 😰

To build and test our backend we’ll use a jar file, which we will create with the help of shadowJar library.

First, let’s add the Shadow Jar version to the Versions.kt:

const val SHADOW_JAR_VERSION = "7.1.1"

And then to configure it in backend build.gradle.kts add the following to the plugins section:

id("com.github.johnrengelman.shadow") version Versions.SHADOW_JAR_VERSION

This will automatically add a shadowJar task to our project and configure it to include the sources from the main sourceSet. We will also configure the task to set the name and output extension. To do so, first add an import to the top of your build.gradle.kts:

import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar

And then add the configuration after your dependencies in build.gradle.kts:

tasks.withType<ShadowJar> {
   archiveBaseName.set("Backend")
   archiveClassifier.set("")
   archiveVersion.set("")
   isZip64 = true
}

Before we can test our backend let’s implement simple routing. In the Application function install the routing:

import io.ktor.application.*
import io.ktor.routing.*

internal fun Application.module() {
   install(Routing) {
       api()
   }
}

Immediately create a separate Api.kt file, where we’ll list all the routes like this:

import io.ktor.application.*
import io.ktor.response.*
import io.ktor.routing.*

internal fun Routing.api() {
   hello()
}

private fun Routing.hello() {
   get("/hello") {
       call.respondText("Hello!")
   }
}

Now
(1) rebuild
(2) make the project

rebuild and make

If you get a junit error, then just delete the test folder from the backend module - we will not need it. And try again.

Then check the build folder: here it is, our Backend.jar 🤩

backend jar

Let’s try to start the backend from the command line. First, open the terminal window and go to your KMP project. As mentioned above, we can always pass required parameters to our server application through environment variables. For example, we can override the port that we specified in application.conf:

java -jar ./backend/build/libs/backend.jar -port=9000

Then open your web browser at localhost:9000/hello. If it greets you, then it’s a good sign!

hello

Congrats, we’ve created a simple backend REST API with our first get function!
You can reward yourself with a slice of pizza now.