The complete source code for this project is available on GitHub.

Introduction

You may already be enjoying the power and simplicity of Kotlin for writing Android applications but it turns out it’s also a very capable back-end language.

To demonstrate how straightforward it can be, we will take 15 minutes and build a simple API, a coin flipper.

When /flip is called it will simply return the result of a randomised coin flip:

curl localhost:8080/flip {

"face": "TAILS"

}

We will cache the previous results in an in-memory database, the contents of which can be retrieved by calling /outcomes:

curl localhost:8080/outcomes [

{

"face": "HEADS"

},

{

"face": "TAILS"

},

{

"face": "HEADS"

}

]

Photo by Ryan Thomas Ang on Unsplash

Components

For the server we will use Ktor, a framework from JetBrains. It makes setting up a server and adding functionality extremely straightforward.

For the database access we will use Exposed, another JetBrains creation which wraps a JDBC driver to expose SQL functionality in Kotlin.

For the in-memory database we will use H2, a lightweight java implementation.