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

API GATEWAY: THE CLOUDFRONT 403 FORBIDDEN ERROR

If you are having a 403 Forbidden error from CloudFront , that means your domain name is not linked to your CloudFront distribution and because CloudFront stays in front of your API GATEWAY you need to create a CNAME record pointing your domain name to your CloudFront target domain name in order for it to work. So, If you need to point your api to a custom domain name, all you have to do is following those 2 easy steps: 1 - CREATING YOUR CUSTOM DOMAIN NAME Go to the API GATEWAY console and click on the Custom Domain Name menu. Click on the Create Custom Domain Name button. Next, assign a certificate matching the same domain name you are creating and map to the root path and destination of your desired api. Lastly, copy the CloudFront Target Domain Name . You will need to paste that in your Route 53 record. 2 - CREATING A CNAME RECORD ON ROUTE 53 Create a CNAME record on Route 53 for the same custom domain name, assigning to it the CloudFront Target Domain. CONCLUSION ...