Build a RESTful Web Service with Kotlin

Introduction

Spring and Kotlin combine together to create a powerhouse when it comes to rapid application development. The Spring project is a powerful framework that allows you to develop an application quickly with as little boilerplate and configuration code as possible. Kotlin is a language that is developed Jetbrains that focuses on code readability and conciseness. This guide will show you how to build a RESTful web service using Spring Boot and Kotlin.

Getting Started

We will use a Maven project to mranage the resources that this application will need. Your project will need the following folder skeleton before you can continue.

Maven

After you have created your project skeleton you can continue.

pom.xml

The pom.xml file is used by Maven to manage all of your project dependencies. You can copy and paste this code into your pom.xml file, which will pull in all of the Spring Boot and Kotlin dependencies.



    4.0.0

    stonesoupprogramming
    BuildingRESTfulWebService
    1.0-SNAPSHOT

    
        1.2.31
    

    
        org.springframework.boot
        spring-boot-starter-parent
        2.0.0.RELEASE
    

    
        
            org.jetbrains.kotlin
            kotlin-stdlib-jdk8
            ${kotlin.version}
        
        
            org.jetbrains.kotlin
            kotlin-reflect
            ${kotlin.version}
        
        
            org.reflections
            reflections
            0.9.10
        
        
            org.jetbrains.kotlin
            kotlin-test
            ${kotlin.version}
            test
        

        
            org.springframework.boot
            spring-boot-starter-web
        
        
            org.springframework.boot
            spring-boot-starter-test
            test
        
        
            com.jayway.jsonpath
            json-path
            test
        
    

    
        src/main/kotlin
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
            
                org.jetbrains.kotlin
                kotlin-maven-plugin
                ${kotlin.version}
                
                    
                        compile
                        compile
                        
                            compile
                        
                    
                    
                        test-compile
                        test-compile
                        
                            test-compile
                        
                    
                
                
                    1.8
                
            
        
    

    
        
            spring-releases
            https://repo.spring.io/libs-release
        
    
    
        
            spring-releases
            https://repo.spring.io/libs-release
        
    

Application.kt

Kotlin is a language that is meant to be concise, which plays to our advantage. We will hold all of our classes inside of the Application.kt file.

package com.stonesoupprogramming.spring.boot

import org.springframework.boot.SpringApplication
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.RestController
import java.util.concurrent.atomic.AtomicLong

/**
 * This class gets converted into JSON and serves as our data model.
 * We can use Kotlin's data class feature to make it only one line of code.
 */
data class Greeting (val id : Long, val content : String)

/**
 * The @RestController annotation tells the Spring Environment to
 * use this class to handle REST requests. That means that it will handle
 * HTTP requests but does not use a view technology to write the response.
 * Instead, an instance of Greeting is simply converted into JSON and written
 * to the HTTP response body.
 */
@RestController
class GreetingController {

    private val counter : AtomicLong = AtomicLong()

    /**
     * The @RequestMapping signals that this method will handle
     * HTTP requests to /greeting. We can narrow it down to GET, POST, PUT, etc
     * when we want different methods to handle different requests
     * at this endpoint.
     *
     * The name parameter is annotated with @RequestParam which has
     * two arguments. The name argument maps the request parameter name to
     * the name argument in this method. The defaultValue will populate
     * name with the value "World" if the request does not have a name argument.
     */
    @RequestMapping("/greeting")
    fun greeting(@RequestParam(value="name", defaultValue="World") name : String) : Greeting {
        return Greeting(counter.incrementAndGet(), "Hello $name")
    }
}

/**
 * The @SpringBootApplication is a meta annotation that makes
 * this application executable.
 */
@SpringBootApplication
open class Application

/**
 * Now we just need an entry point to the program.
 */
fun main(args : Array){
    SpringApplication.run(Application::class.java, *args)
}

Let’s break the code down into each piece.

Greeting

Greeting is a data class that has two fields, id and content. Kotlin introduced data classes to cut down on boilerplate code when using POJOs (Plain old java object). It will have all of the getters, equals, hashcode, and toString() as well as a constructor. This class will get converted into JSON and written to the response body later on in the application.

GreetingController

Spring works on a Model, View, Controller architecture so it uses Controller classes to map web requests to backend code. In this case, we are using @RestController to specify that we are not using a view technology to generate HTML and are instead going to write JSON to the HTML response body.

This class only has one method, greeting, which is annotated with @RequestMapping. You will use @RequestMapping to map HTTP requests to a method in the class. In our case, we are mapping all requests (GET, PUT, POST, DELETE) to /greeting to our greeting method. The greeting method has one argument, name, which is also annotated with @RequestParam.

The @RequestParam has two arguments, value which specifies the name of the argument in the request and the default value if the argument is not present in the request. In our case, we also called the request parameter name and we have it default to World. Inside of the method, we return a new instance of Greeting and then return it. The Spring environment will see to the details of converting it to JSON and writing it to the response.

Application

We also have an empty Application class that is marked with the @SpringBootApplication annotation. This is a meta-annotation that pulls in all of the annotations that are needed to make this program executable. We using it in the main function to start the program.

Finishing

After you start the application, you can point your browser to

http://localhost:8080/greeting and then http://localhost:8080/greeting?name=User to see the JSON output of this application.

Sources

https://spring.io/guides/gs/rest-service/

https://kotlinlang.org/docs/reference/

Source

The source code for this project is available on my github here: https://github.com/archer920/BuildingRESTfulWebService

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s