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
Post a Comment