Builduing Restful Web Services in kotlin using Spring Boot Tutorial

If you are just stating learning server side development / Backend development I strongly suggest you to use Kotlin with Spring Boot.
This article will cover your following questions:
  • How to create restful web service using spring framework in Kotlin.
  • How to build microservices using spring boot framework in Kotlin.
  • How to run spring boot application.
  • Spring Boot Restful API Kotlin Tutorial.
  • Spring Boot IntelliJ IDEA Gradle Setup + Kotlin
  • Spring Boot database connection setup.
What we will do in this tutorial:
  • We will develop RESTFUL API with Spring Boot framework in Kotlin.
  • We will use SqlYog Database management for working with MYSQL Database in our Spring Boot Kotlin Application.
  • We will create Employee Database and we will build microservices (CRUD).
  • We will develop Rest API for Getting the list of all employees from the database using Kotlin Spring Boot.
  • We will develop Rest API for Adding new employees to the database using Kotlin Spring Boot.
  • We will develop Rest API for Updating employee in the database using Kotlin Spring Boot.
  • We will develop Rest API for Deleting an employee from the database using Kotlin Spring Boot.

Let’s start:-

Creating new Spring Boot Kotlin Project in IntelliJ IDEA (Step-1).

Start IntelliJ IDEA and select create new project. Select Gradle from project templates and check Kotlin(Java) from additional libraries and frameworks list. And click Next.
spring boot kotlin
spring boot new project kotlin

Creating new Spring Boot Kotlin Project in IntelliJ IDEA (Step-2).

Enter GroupId and ArtifactID like below and click Next.
enter group id and artifact id spring boot
Enter spring boot group id and artifact id for project

Creating new Spring Boot Rest API using Kotlin Project in IntelliJ IDEA (Step-3).

Make sure JDK path is set. Click Next.
setup jdk and gradle path spring boot
setup JDK and Gradle home path IntelliJ IDEA

Creating new Restful webservice Spring Boot Kotlin Project in IntelliJ IDEA (Step-4).

Enter Project name and click Finish.
spring boot restful web service tutorial
Enter Project Name and Click Next

Setup Gradle dependencies for Kotlin-Spring

Now we will add required spring boot and Kotlin dependencies and Kotlin-Spring plugin. Open build.gradle file and paste below code.
Make sure you do not override groupdId. (replace groupdId with your project group id)
group 'com.developine'
version '1.0-SNAPSHOT'
buildscript {
    ext.kotlin_version = '1.2.30' // Required for Kotlin integration
    ext.spring_boot_version = '1.5.4.RELEASE'
    repositories {
        mavenCentral()
        jcenter()
    }
    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" // Required for Kotlin integration
        classpath "org.jetbrains.kotlin:kotlin-allopen:$kotlin_version"
        classpath "org.springframework.boot:spring-boot-gradle-plugin:$spring_boot_version"
    }
}
apply plugin: 'kotlin'
apply plugin: "kotlin-spring" 
apply plugin: 'org.springframework.boot'

repositories {
    mavenCentral()
}
dependencies {
    compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version"
    compile 'org.springframework.boot:spring-boot-starter-web'
}

compileKotlin {
    kotlinOptions.jvmTarget = "1.8"
}
compileTestKotlin {
    kotlinOptions.jvmTarget = "1.8"
}

Creating Required Directories and Packages in our Kotlin Restful web service Spring Boot Project:

Right click on project and create new directory src , than right click src and create new directory under main. Than create new directory kotlin. under Kotlin direcoty create new package restapi .

Kotlin Spring Boot Restful WebService project structure:

Your project structure should look like below.
kotlin spring boot web service
project structure

Creating Application Class:

Now we need Application Starter class. Like any Java/Kotlin program which requires main() method to start execution. Spring Boot applications also need a public static main method, we also annotate this class with @SpringBootApplication annotation. Create new class inside restapi package. and name it ApplicationClass.kt.
package restapi

import org.springframework.boot.SpringApplication
import org.springframework.boot.autoconfigure.SpringBootApplication

@SpringBootApplication
class ApplicationClass {

}

fun main(args: Array) {
    SpringApplication.run(ApplicationClass::class.java, *args)
}

Running Restful web service Kotlin Spring Boot Application:

Now we are done with creating hello word Restful API. If we run above ApplicationClass, we will get below output which will let us know that our configurations are correct. It will show us that Tomcat server is running on port 8080.
kotlin spring boot restful webservice tomcat server
Tomcat server running on port 8080

Now we will start developing Employees RESTFUL API (CRUD).

We will use MYSQL Database.
  …………………………

In this tutorial, we will create a Restful web service using spring boot in Kotlin. we will also set up MySQL database in our project.

I assume you have the basic understanding of Kotlin, Spring Boot, Restful Web Services, MySQL database, Gradle.

I am using Intellij Idea for development.

Step 1:-

Create new Gradle project and select Kotlin from additional libraries and frameworks list.

Step 2:-

Setup groupId and artifactId and click next.

Next steps:-

Spring Boot Gradle setup in Intellij Idea for Restful web services
gradle setup in kotlin for spring boot and mysql
setup build.gradle file like this. add required dependencies for spring boot gradle plugin.
group 'com.titleapps'
version '1.0-SNAPSHOT'
buildscript {
    ext.kotlin_version = '1.1.4-3' // Required for Kotlin integration
    ext.spring_boot_version = '1.5.4.RELEASE'
    repositories {
        mavenCentral()
        jcenter()
    }
    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" // Required for Kotlin integration
        classpath "org.jetbrains.kotlin:kotlin-allopen:$kotlin_version"
        // See https://kotlinlang.org/docs/reference/compiler-plugins.html#kotlin-spring-compiler-plugin
        classpath "org.springframework.boot:spring-boot-gradle-plugin:$spring_boot_version"
    }
}
apply plugin: 'kotlin'
apply plugin: "kotlin-spring" // See https://kotlinlang.org/docs/reference/compiler-plugins.html#kotlin-spring-compiler-plugin
apply plugin: 'org.springframework.boot'
repositories {
    mavenCentral()
}
dependencies {
    compile "org.jetbrains.kotlin:kotlin-stdlib-jre8:$kotlin_version"
    compile 'org.springframework.boot:spring-boot-starter-web'
    // JPA Data (We are going to use Repositories, Entities, Hibernate, etc...)
    compile 'org.springframework.boot:spring-boot-starter-data-jpa'
    // Use MySQL Connector-J
    compile 'mysql:mysql-connector-java'
}

compileKotlin {
    kotlinOptions.jvmTarget = "1.8"
}
compileTestKotlin {
    kotlinOptions.jvmTarget = "1.8"
}
project directory structure.

First create a new package inside main. “restapi” in this case.

Than create an Application class. which be responsible to start our project.

Add this code in Application class. Note: Application class will not be inside any package. it will be in root package.

package restapi

import org.springframework.boot.SpringApplication
import org.springframework.boot.autoconfigure.SpringBootApplication

@SpringBootApplication
class Application {

}

fun main(args: Array) {
    SpringApplication.run(Application::class.java, *args)
}

Above Application.kt class will start everything including embedded web server.

Now we will add a controller class inside controller package. controller class will know how to handle web requests.

We will develop three rest web services in this project.

  1. Get user name, user email from request params and save user in Database.(REQUEST METHOD = GET)
  2. Submit feedback from any user in database. in this API we will get feedback params from RequestBody. (REQUEST METHOD = POST)
  3. Get all saved users from Database and return list of all users.
Create Entity Classes

For above three API’s we need to define Entity classes. which will be converted automatically into a Table.

import javax.persistence.Entity
import javax.persistence.GenerationType
import javax.persistence.GeneratedValue;
import javax.persistence.Id


@Entity
class User() {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    val id: Int? = 0
    lateinit var name: String
    lateinit var email: String

    constructor(name: String, email: String) : this() {
        this.name = name
        this.email = email
    }
}

user id is autogenerated. note @Entity annotation.

Now UserFeed class

import javax.persistence.Entity
import javax.persistence.GeneratedValue
import javax.persistence.GenerationType
import javax.persistence.Id

@Entity
class UserFeedback() {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    val id: Int? = 0
    lateinit var email: String
    lateinit var stars: String
    lateinit var feedback: String
    lateinit var fcm_token: String
    lateinit var deviceId: String

    constructor(email: String, stars: String, feedback: String, fcm_token: String, deviceId: String) : this() {
        this.email = email
        this.deviceId = deviceId
        this.fcm_token = fcm_token
        this.feedback = feedback
        this.stars = stars
    }
}

Now create a Repository interface which will handle CRUD.

import org.springframework.data.repository.CrudRepository
import restapi.model.User

interface UserRepository : CrudRepository {
}

Above interface will be automatically implemented by a bean, and you can call its utility methods from your controller class.

Now we will add controller class. As I mentioned earlier controller class is responsible to accept and handle API requests.

@RestController  // means this is controller class
@RequestMapping("/api/v1")  //url starts with /api/v1 after app path 
class RestApiController {

// To get the bean named userRepository
@Autowired lateinit var userRepo: UserRepository

// Add new user in DATABASE API.
@GetMapping(path = arrayOf("/add")) // Map ONLY GET Requests
@ResponseBody
fun addNewUser(@RequestParam name: String, @RequestParam email: String): String {
   if (name == "" || email == "") {
       // Exception handling explained at the end of this class.
        throw IllegalArgumentException("invalid input.")
    } else {
        val n = User(name, email)
        n.name = name
        n.email = email
        userRepo.save(n)
        return "Saved"
    }
}
GET LIST OF ALL — USERS API
@GetMapping("/users/getuser")
fun getAllUsersFromDb(): Any {
    return userRepo.findAll()
}
// ADD BELOW CODE IN YOUR CONTROLLER CLASS FOR EXCEPTION HANDLING in Spring Boot.
// YOU CAN ADD MULTIPLE METHODS FOR HANDLING DIFFERENT TYPES OF
// EXCEPTION IN YOUR SPRING BOOT PROJECT.
@ExceptionHandler(IllegalArgumentException::class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
fun handleIllegalArgumentError(e: IllegalArgumentException) = e.message }
Provide Database Credentials for CRUD operations in Spring Boot

Now last thing is create a new resource file in resources folder. and name it application. and add this in application.properties file.

spring.jpa.hibernate.ddl-auto=create
spring.datasource.url=jdbc:mysql://localhost:3306/database_name
spring.datasource.username=root
spring.datasource.password=

Before this make sure you have created database. you can use SQLyog for this purpose.

https://github.com/hammad-tariq/kotlin-spring-boot-resful-mysql-demo

Congrats!

You have learned how to create a restful web service in Kotlin using spring boot. and How to setup database in your spring boot project. If you’re planning on using these web services and the database for any reason, you may want to look into api testing services to ensure your newly built API is running how it should be.

Recommended Reading:- Kotlin Idioms Tutorial Kotlin for iOS Application Development

If you have any confusion/feedback please write in comments section. Thank you.

Contact Us