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

Log Aggregation with ELK stack and Spring Boot

Introduction In order to be able to search our logs based on a key/value pattern, we need to prepare our application to log and send information in a structured way to our log aggregation tool. In this article I am going to show you how to send structured log to ElasticSearch using Logstash as a data pipeline tool and how to visualize and filter log information using Kibana. According to a definition from the Wikipedia website: Elasticsearch is a search engine based on the Lucene library. It provides a distributed, multitenant-capable full-text search engine with an HTTP web interface and schema-free JSON documents. According to Elasticsearch platform website , Elasticsearch is the heart of the Elastic stack, which centrally stores your data for lightning fast search. The use of Elasticsearch, Kibana, Beats and Logstash as a search platform is commonly known as the ELK stack. Next we are going to start up Elasticsearch, Kibana and Logstash using docker so we can better underst...

How to create a REST API Pagination in Spring Boot with Spring HATEOAS using MongoDB

Introduction In this post we are going to see how we can create a REST API pagination in Spring Boot with Spring HATEOAS and Spring Data MongoDB . For basic queries, we can interact with MongoDB using the MongoRepository interface which is what we are going to use in this tutorial. For more advanced operations like update and aggregations we can use the MongoTemplate class. With Spring applications we start adding the needed dependencies to our pom file if using Maven as our build tool. For this project we are going to use the following dependencies: Spring Web , Spring Data MongoDB and Spring HATEOAS . To quickly create your Spring Boot project with all your dependencies you can go to the Spring Initializr web page. This is how your project should look like: As with any MVC application like Spring there are some minimal layers that we need to create in our application in order to make it accessible like the Controller , Service , Model and Repository layers . For this...

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