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

Python Color Chooser

The tkinter library in Python comes with an askcolor function that will pull up the system’s color picker dialog. It’s really easy to use and it returns a tuple with a RGB value and a hexadecimal value. This makes it really easy for anyone who is working with colors to ask the user for a color.

from tkinter import *
from tkinter.colorchooser import askcolor


class Window(Frame):
    def __init__(self, master=None, cnf={}, **kw):
        super().__init__(master, cnf, **kw)
        self.open = Button(self, text='Pick a color', command=self.pick_a_color)
        self.exit = Button(self, text='Exit', command=self.quit)

        for b in (self.open, self.exit):
            b.pack(side=LEFT, expand=YES, fill=BOTH)
        self.pack()

    def pick_a_color(self):
        print(askcolor(parent=self, title='Pick a color'))


if __name__ == '__main__':
    win = Window(Tk())
    win.mainloop()

askcolor

The askcolor function simply shows the system’s ask color dialog window. Therefore, it will adjust to the user’s platform and look natural. You can add the parent and title arguments if you want but otherwise the defaults work just as well.

Calling the function only requires one line of code.

askcolor(parent=self, title='Pick a color')

When the user picks a color, a tuple is returned with the rgb values and the hexadecimal values.

((255.99609375, 170.6640625, 104.40625), '#ffaa68')

You will get this result if they click on cancel.

(None, None)

Notice that it is a tuple of None.

Python File Dialog

Many Python applications need to ask the user if they want to a open a file or folder or save a file. The tkinter library has built in dialog functions for this exact purpose. Here is an example of how to use the askopenfilename, asksaveasfile, and askdirectory functions with some common configurations.

from tkinter import *
from pathlib import Path
from tkinter.filedialog import askopenfilename, asksaveasfile, askdirectory


class Window(Frame):
    def __init__(self, master=None, cnf={}, **kw):
        super().__init__(master, cnf, **kw)
        self.open = Button(self, text='Open', command=self.open_file)
        self.save = Button(self, text='Save', command=self.save_file)
        self.ask_dir = Button(self, text='Folder', command=self.ask_folder)
        self.exit = Button(self, text='Exit', command=self.quit)

        for b in (self.open, self.save, self.ask_dir, self.exit):
            b.pack(side=LEFT, fill=BOTH)

        self.pack()


    def open_file(self):
        file = askopenfilename(filetypes=(("Python files", "*.py"),
                                           ("All files", "*.*")),
                               title='Open File',
                               initialdir=str(Path.home()))
        if file:
            print(file)
        else:
            print('Cancelled')

    def save_file(self):
        file = asksaveasfile(filetypes=(("Python files", "*.py"),
                                           ("All files", "*.*")),
                               title='Save File',
                               initialdir=str(Path.home()))
        if file:
            print(file)
        else:
            print('Cancelled')

    def ask_folder(self):
        folder = askdirectory(title='Pick a folder', initialdir=str(Path.home()))

        if folder:
            print(folder)
        else:
            print('Cancelled')


if __name__ == '__main__':
    win = Window(Tk())
    win.mainloop()

askopenfilename

You use askopenfilename when you want to open a file. It will return the absolute path of the file as a string if the user picks a file, or it will return None if the user cancels. You can restict the file types by passing an Iterable of tuples to the filetypes argument. If you do not specify an initialdir argument, it will default to the root of the user’s disk. I usually prefer to set it to the user’s home directory using Path.home() but you can adjust this to your application’s needs. The dialog will look specific to the user’s platform.

def open_file(self):
    file = askopenfilename(filetypes=(("Python files", "*.py"),
                                       ("All files", "*.*")),
                           title='Open File',
                           initialdir=str(Path.home())
    if file:
        print(file)
    else:
        print('Cancelled')

asksaveasfile

You can use this dialog when you want to perform a save operation. It takes arguments that are similar to askopenfilename, but it will return a file handler object opened in write mode (if you use the default arguments) rather than a string. You can then proceed with your save code. This function also returns None if the user cancels.

def save_file(self):
    file = asksaveasfile(filetypes=(("Python files", "*.py"),
                                       ("All files", "*.*")),
                         title='Save File',
                         initialdir=str(Path.home()))
    if file:
        print(file)
    else:
        print('Cancelled')

askdirectory

This function is used to let the user pick a folder. It will return a string if the user picked a folder or None if they chose to cancel.

def ask_folder(self):
    folder = askdirectory(title='Pick a folder', initialdir=str(Path.home()))

    if folder:
        print(folder)
    else:
        print('Cancelled')