Ktor for fast server prototyping

Jarosław Michalik
Kt. Academy
Published in
4 min readOct 28, 2019

--

Photo by Mark Seletcky on Unsplash

Ktor is a framework for creating server and client applications in Kotlin. As the creator says — its ultimate goal is to provide end to end solution for connected multiplatform apps.

In this article you will find basics of Ktor setup and implementation for simple server application.

Installation

For fast prototyping you often don’t have to create a new project — you may even add Ktor module as a Gradle subproject in an Android project. The most basic build.gradle with Ktor dependency will look like this:

You should also define application.conf file in src/resources, so the application plugin would know how to start your app:

Implementation

Up and running

Let’s start with a simple endpoint that will return predefined value and Http status code:

Let’s test this endpoint locally. Execute ./gradlew run and wait for an application to start. Then use curl or your favorite rest client and see what happens:

$ curl -i localhost:8080/
HTTP/1.1 200 OK
Content-Length: 13
Content-Type: text/plain; charset=UTF-8
Test message

We received a raw text response. In an application client side we don’t like text responses, we use JSON everywhere. How to return JSON from your API? Nothing easier. We will make the use of one of Ktor JSON features.

Feature in KTOR is pluggable dependency — in most cases, it intercepts request and response and is able to do something with them. In application DSL we add the feature using install function.

Add dependency:

implementation "io.ktor:ktor-gson:$ktor_version"

And install the feature in Application:

As you can see, there is mapOf("status" to "Test message") added — Gson will parse that structure to readable Json.

Rebuild the project and test your endpoint again:

$ curl -i localhost:8080/
HTTP/1.1 200 OK
Content-Length: 25
Content-Type: application/json; charset=UTF-8
{"status":"Test message"}

Create, read, update, delete

To work with CRUD functionalities we will use the following repository with in-memory data source implementation:

Create & update — receive function

We will create post route where we will receive a proper Item, add the Item to repository and respond with some result:

We are using io.ktor.reqeust.receive<*> function on our call — since we have added gson() in the previous steps, JSON item will be converted to Item data class.

$ curl -i -XPOST -H "Content-type: application/json" 
-d '{
"id":"3",
"message":"First message"
}'
'localhost:8080/items'

What should return:

HTTP/1.1 201 Created
Content-Length: 36
Content-Type: application/json; charset=UTF-8
{"id":"3","message":"First message"}

Delete — call parameters

To create delete endpoint we will make use of call parameters property.

As you can see, we defined {id} in the path definition. Ktor is able to recognize and retrieve path parameter so we could use it later.

Read — get

Finally, let’s implement get endpoint which will retrieve a full list of items:

And after executing GET on /items you should receive all items you’ve put into the repository:

$ curl -i localhost:8080/items
HTTP/1.1 200 OK
Content-Length: 77
Content-Type: application/json; charset=UTF-8
[{"id":"3","message":"First message"},{"id":"23","message":"Second message"}]

Summary

  • ✔ Kotlin first — there is no need to handle complex Java based APIs
  • ️✔ Easy to start with — ready to go with one dependency
  • ✔ Readability — what you see is what you get. Routing DSL is quite an elegant way to define endpoints
  • ❌ Not as many integrations as Spring
  • ❌ No golden standards yet

Previously my first choice tool for API prototyping was express.js — now Ktor took its place. I find it super easy to use — almost every functionality works as I would expect it to behave. For bigger projects I would still use Spring — it’s much more mature and has a lot of integrations.

Those pros and cons are only my humble opinion. You should see yourself how Ktor can serve you on the backend and frontend side.

Click the 👏 to say “thanks!” and help others find this article.

To be up-to-date with great news on Kt. Academy, subscribe to the newsletter, observe Twitter and follow us on medium.

If you need a Kotlin workshop, check how we can help you: kt.academy.

--

--