Skip to main content

How to create a Rest API in Kotlin using KTOR

If you came from a Java background you may be interested to know how you can build a rest api in kotlin. In this post we will create one using Ktor, but wait, what is ktor? According to their web site:
Ktor is an asynchronous framework for creating microservices, web applications, and more. It’s fun, free, and open source.

Just like any Java Spring Boot Application, Ktor also has its own Application file. So lets start from it by comparing a spring boot application file with a Ktor.

A Ktor application file:

As you can see, both files have a main method that receives as an argument an array of strings, but Ktor uses its main method to create an embedded netty application.

In a Spring Application we would create a controller class responsible to handle all http requests to an endpoint by making use of java annotations. In Ktor, we need to create a kotlin file to represent our Application Routes by using the Ktor Route class. As you can see we make use of the route method to define our endpoint as well as all our http methods.

Next we need to work in each individual http request. Lets start with our GET request. But before we do so we need to create a data class in the same way we would create our POJO for our model or entity class in Spring. So, lets do just that:

By adding the val in front of each constructor parameter we are turning them into class properties so we don´t have to write any getters or setters to them, but in doing so we are actually using a Kotlin convention to create immutable and safer objects. Adding the serializable annotation to our data class will let Ktor know how to handle the serialization properly for us so we can just use our kotlin object to answer to the http request. So lets see how that work in code by changing our get handler in the userRoutes.kt file:

As you can see, we can just use the call.respond function to answer to the http get request by passing a kotlin object to it and if our list of users are empty we can just use the call.respondText function to respond with a plain text message and an optional http status code, because the default value is HttpStatusCode.OK. So, before we do just that, lets create a mutable list of users so we can use them in our post handler to add new users!

Instead of using the call.respond function as we would normally do it in a get request we can now make use of the call.receive function and since we have annotated our data class as serializable, we can now automatically deserialize the JSON request body into a Kotlin User object and use it to add it to our list of users.

In the next post we will register our user route and finish our user rest endpoint by making the code of the get handler that accepts an id as a path parameter and we are also going to add the code of the delete handler.

Comments

Popular posts from this blog

How to use Splunk SPL commands to write better queries - Part I

Introduction As a software engineer, we are quite used to deal with logs in our daily lives, but in addition to ensuring that the necessary logs are being sent by the application itself or through a service mesh, we often have to go a little further and interact with some log tool to extract more meaningful data. This post is inspired by a problem I had to solve for a client who uses Splunk as their main data analysis tool and this is the first in a series of articles where we will delve deeper and learn how to use different Splunk commands. Running Splunk with Docker To run Splunk with docker, just run the following command: docker run -d —rm -p 8000:8000 -e SPLUNK_START_ARGS=--accept-license -e SPLUNK_PASSWORD=SOME_PASSWORD --name splunk splunk/splunk:latest Sample Data We are going to use the sample data provided by Splunk. You can find more information and download the zip file from their web site . How does it work? In order to be able to interact with Splunk t...

How to become a Blockchain developer and write your first Smart Contract

Introduction This is an introductory article to help you understanding the tools and frameworks needed so that you can know from where and how to start creating your own Smart Contracts. In this post I will give you an overview of the tools, frameworks, libraries and languages used to create a Smart Contract in the Ethereum Blockchain . In the second part of this article, we are going to see how to create a Smart Contracts using Solidity and ee are also going to see how to run a Blockchain locally using Ganache , so that you can deploy, interact and test your Smart Contract in your local development environment. According to a definition from the Wikipedia website: A blockchain is a decentralized, distributed, and often public, digital ledger consisting of records called blocks that are used to record transactions across many computers so that any involved block cannot be altered retroactively, without the alteration of all subsequent blocks.. What do you need to know? T...

How to run OPA in Docker

From the introduction of the openpolicyagent.org site: OPA generates policy decisions by evaluating the query input against policies and data. In this post i am going to show you an easy and fast way to test your policies by running OPA in Docker. First, make sure you have already installed Docker and have it running: docker ps Inside your choosen directory, create two files. One called input.json file for your system representation and one file called example.rego for your rego policy rules. Add the following content to your json file: Add the following content for the example.rego: Each violation block represents the rule that you want to validate your system against. The first violation block checks if any of the system servers have the http protocol in it. If that is the case, the server id is added to the array. In the same way, the second violation block checks for the servers that have the telnet protocol in it and if it finds a match the server id is also...