Ktor — Kotlin for backend development
Let’s discuss how to start with ktor-kotlin for backend with the project setup ⚙
At ScaleReal, we have been using Kotlin for backend development for a long time now and we love it. We initially used the Micronaut framework for developing our microservices in Kotlin but recently started working on Ktor for a few of our new microservices. So far we have been loving the experience. So, we wanted to share that with the world.
When we talk about backend technology, we have a lot of general-purpose languages like Go, Java, Python, and so on Yet, when we talk about Kotlin as a backend language, it raises plenty of eyebrows 🤨.
What is Kotlin?
Kotlin is a broadly useful, free, open-source, statically composed “pragmatic” programming language at first intended for the JVM (Java Virtual Machine) and Android that combines object-oriented and functional programming paradigms. The Android world is comfortable with Kotlin as the best option for application development.
With Kotlin gaining enormous popularity, it was extended to build cross-platform apps for platforms like iOS, Web, and even Desktop.
Can we really use Kotlin in the backend?
Alright, presently the billion-dollar question? Would we be able to involve Kotlin for Backend? Or on the other hand, is Kotlin production prepared/ready?
The short answer is, Yes and totally Yes.
Why you should consider Kotlin as your next backend language?
You may wonder why should you consider Kotlin for the backend.
For that, let me assist you with this:
Kotlin is a great fit for developing server-side applications. It allows you to write concise and expressive code while maintaining full compatibility with existing Java-based technology stacks, all with a smooth learning curve:
- Expressiveness: Kotlin’s innovative language features, such as its support for type-safe builders and delegated properties, help build powerful and easy-to-use abstractions.
- Scalability: Kotlin’s support for coroutines helps build server-side applications that scale to a massive number of clients with modest hardware requirements.
- Interoperability: Kotlin is fully compatible with all Java-based frameworks, so you can use your familiar technology stack while reaping the benefits of a modern language.
- Migration: Kotlin supports the gradual migration of large codebases from Java to Kotlin. You can start writing new code in Kotlin while keeping older parts of your system in Java.
- Tooling: In addition to great IDE support in general, Kotlin offers framework-specific tooling (for example, for Spring) in the plugin for IntelliJ IDEA Ultimate.
👀 Overview
let’s build the sample project with ktor-kotlin for backend with the basic project setup ⚙️
Technology/Tools used
- Kotlin: Programming languages for development
- Ktor: Backend development framework
⚙️ What is Ktor?
Ktor is an asynchronous web framework written and designed in Kotlin. It gives us the ability to create client and server-side applications that can run and target multiple platforms while making use of the impressive features of Kotlin such as Coroutines.
So we are going to use IDE ‘IntelliJ IDEA’, You will have to install the plugin start.ktor.io to create a Ktor project. On installation, you will be able to see a separate entry in the ‘Create New Project’ menu.
Getting started with the Ktor server
Create a new Ktor project -
To create a new Ktor project, open IntelliJ IDEA
1. click on the new project available on the welcome screen / Go to File -> new -> project -> Ktor
- Name: It is used to define the name for the project
- Location: It is used to specify the path in the local PC/Mac where we want to store the project.
- Build System: It means the build system responsible to build the project. In our case, we will use Gradle Kotlin.
- Website: This is the website we will use to generate project Artifact.
- Artifact: This is only read-only generated via the Website you entered.
- Ktor Version: This is used to specify the version we will use for Ktor. In our case, we will use 1.6.10, the latest version.
- Engine: This is one of the most important parts of creating the project. This will be used to run the server. We will select Netty
- Configuration in: This is used to say, that where do we need to store server variables.
- Add Sample code: This will be used to add some dummy code to the project.
2. Add the required plugin, for now, I added the Routing and kotlinx.serialization then finish the project creation -
- Routing -
Routing is a plugin that is installed into an Application to simplify and structure page request handling. Extracting information about a request, and generating valid responses inside a route, is described on the requests and responses pages.
For more details, refer to the official doc
- kotlinx.serialization
ContentNegotiation allows you to use content converters provided by thekotlinx.serialization
library. This library supportsJSON
,CBOR
,ProtoBuf
, and other formats.
Application -
The Application.kt contains the main fun is used to configure server parameters in code and run an application.
Routes -
The Application.configureRouting() is an extention function that handle the route
Routing.kt is the default file generated with the project build, we can change and define our routes in this file.
Response pipeline couldn’t transform ‘*class java.util.ArrayList*
' to the OutgoingContent
The reason is that the project can’t serialize
the list as Output.
To fix it we need to install Content Negotiation. To do this we will go to our Routing file and install it
Let’s start with how to run the project -
In the above image this is the basic structure of the project — In src Directory we have two modules main and test. The main module contains the code of the project and the test module will have the tests for code
Now we are ready to run the project and see the output, you can run the project by clicking run on IntelliJ. OR run the command in terminal ` ./gradlew run `
After a successful run, you will see the following output in the terminal
When you click on the URL, you will see the output “Hello World!” 🎉
Let’s go now, we can play with the code and build some of our own APIs -
In this part, we are going to see how to create our own custom routes, we will build the custom Employees Route
- GET — List of All Employees
- POST — Create new Employee
We need to create a model first for the Employee which contains id, name, age, address
In this sample project, we won’t use any database, we are going to use it for simulating the structure list(MutableList) type structure which will be responsible for adding employees.
- POST(“/employee”) — Create a new employee
we need to do some changes in the serialization.kt file, we are going to add a new endpoint with a post to create a new employee. we will create an employee route with POST requests like:
- Output (POST(“/employee”))
- GET(“/employee”) — Fetch the list of employee
will fetch all employee route with GET requests like:
- Output (GET(“/employee”))
We have finally created all the routes we wanted to do at the start of the blog. This is the basic example to get started with creating routes in Ktor.
Finally, the code in my route looks like this:
📕 Summary -
This is a very beginner-friendly starting point to get started to build your routes in Ktor. Go ahead and build your own. In the upcoming blogs, we will see advanced how to apply the dependency injection in the Ktor project and how to establish the connection with the database.
At Scalereal We believe in Sharing and Open Source.
So, If you found this helpful please give some claps 👏 and share it with everyone.
Sharing is Caring!
Thank you ;)
Sample project with complete code 👇
Reference — https://kotlinlang.org/docs/home.html