Build REST CRUD API's with Kotlin, Spring, and MongoDB

In this article, we will show you how to develop a  REST-style web service with Kotlin, Spring Boot, MongoDB.
A quick overview of Kotlin, Spring Boot, and MongoDB  


It’s a modern programming language targeting the Java platform. Kotlin is concise, safe, pragmatic, and fixated on interoperability with Java code. It can be used virtually everywhere Java is utilized today: for server-side development, Android apps, and much more. Kotlin works great with all subsisting Java libraries and frameworks and runs with the same level of performance as Java. 


MongoDB is a document database built on a scale-out architecture that has to propagate with developers of all kinds who are building scalable applications utilizing agile methodologies.
MongoDB was built for people who are building internet and business applications who need to evolve expeditiously and scale elegantly. If you are doing that, you should consider MongoDB.

Companies and development teams of all sizes use MongoDB because:
  • The document data model is a potent way to store and retrieve data that sanctions developers to move expeditiously.
  • MongoDB’s horizontal, scale-out architecture can fortify astronomically immense volumes of both data and traffic.
  • MongoDB has a great utilizer experience for developers who can install MongoDB and commence inscribing code immediately. 

Spring Boot:

Spring boot to develop REST web services and microservices. Spring Boot has taken the Spring framework to the next level. It has drastically reduced the configuration and setup time required for spring projects. We can set up a project with almost zero configuration and start building the things that actually matter to your application. 

Technologies used :

  • Spring Boot 2.3.7.RELEASE
  • Spring  5.2.12.RELEASE
  • Kotlin 2.11.3
  • MongoDB
  • Maven 3
  • Java 8

After completing this tutorial what we will build? 

We will build REST API  CRUD features: 

  1. GET - Fetch all Employee       :     /api/v1/employees
  2. GET - Get Employee by ID     :     /api/v1/employees/{id} 
  3. POST - Create Employee         :     /api/v1/employees 
  4. PUT - Edit Employee Details   :     /api/v1/employees/{id} 
  5. DELETE - Delete Employee    :     /api/v1/employees/{id} 

Project Directory:


Maven is a powerful project management tool that is based on POM (project object model). It is used for project build, dependency and documentation. 
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns=""
<relativePath/> <!-- lookup parent from repository -->
<description>Demo project for Spring Boot</description>





Creating the Document:

The employee model here is the POJO, We use the annotation @Document to set the collection name that will be used by the model. If the collection doesn’t exist, MongoDB will create it.

import org.bson.types.ObjectId
import org.springframework.web.bind.annotation.CrossOrigin

@Document(collection = "employees")
data class Employee(
var id: String? = ObjectId().toHexString(),
val firstName: String,
val lastName: String,
val emailId: String

Creating the Repository:

The API implementation happens in the repository. It acts as a link between the model and the database and has all the methods for CRUD operations.

import org.springframework.stereotype.Repository

interface EmployeeRepository : MongoRepository<Employee, String>

Creating the Rest Controller:

Rest Controller annotation is mainly used for building restful web services using Spring MVC. The class annotated with @RestController is called Rest Controller. The class annotated with @RestController annotation returns JSON response in all the methods.

import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.*
import java.util.*

class EmployeeController(private val employeeRepository: EmployeeRepository) {

fun getAllEmployees(): List<Employee> =

fun createNewEmployee(@RequestBody employee: Employee): Employee =

fun getEmployeeById(@PathVariable(value = "id") employeeId: String):
ResponseEntity<Employee> {
return employeeRepository.findById(employeeId).map { emp ->

fun updateEmployeeById(@PathVariable(value = "id") employeeId: String,
@RequestBody newEmployee: Employee):
ResponseEntity<Employee> {

return employeeRepository.findById(employeeId).map { existingEmployee ->
val updatedEmployee: Employee = existingEmployee
.copy(firstName = newEmployee.firstName, lastName =
newEmployee.lastName, emailId = newEmployee.emailId)


fun deleteEmployeeById(@PathVariable(value = "id") employeeId: String):
ResponseEntity<Void> {
return employeeRepository.findById(employeeId).map { emp ->


Spring Boot Main Class:

Create the main class SpringbootKotlinCrudApplication.kt in the root package

import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication

class SpringbootKotlinCrudApplication

fun main(args: Array<String>) {


Github repository download link is provided at the end of this tutorial

Local Setup:

Step 1: Download or clone the source code to a local machine.

Spring Boot 

Step 2mvn clean install

Step 3: Run the Spring Boot application
mvn spring-boot:run

Testing API's using Postman

Create an Employee:

Fetch All Employee:

Update Employee:

Delete Employee By Id:

Get Employee By Id:

More Kotlin practice:

Popular posts from this blog

Spring boot video streaming example-HTML5

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Spring Boot + Mockito simple application with 100% code coverage

Spring Boot + OpenCSV Export Data to CSV Example

Custom Exception Handling in Quarkus REST API

DataTable-Pagination example with Spring boot, jQuery and ajax

Registration and Login with Spring Boot + Spring Security + Thymeleaf

Node JS mini projects with source code - free download

Spring boot web project free download:User Registration System

Java - Blowfish Encryption and decryption Example