Build Web Application with Kotlin 1.1.61 and Spring (3 of 4)

Kotlin 1.1.61 + Spring で Web Application を作る (2 of 4) の続きです。

Build Web API

HTMLで表示するViewは作りましたから、次は API を作ります。 一覧が取得できる簡単な API を考えます。

Return value of the controller method can be Kotlin Map, which will be converted well to JSON. To be flexible, to make JSON structure changeable, create TaskJsonView object and add method to return the Map, not data class.

Create View to Return JSON

In Kotlin, we can define map with mapOf function, so we can build the map corresponding to the JSON in looking JSON like structure. Of course, we can use MutableMap and add items one by one.

Use TaskJsonView in TaskController. Add the following method to TaskController.

Launch the server and send GET request to http://localhost:8080/task for the JSON, then the following data will be returned. You must add "Accept=application/json" to request header.

Here, the application returns actual data with the format {"data": { ... }}. This structure is the same in the whole application, then let’s extract the structural part to LayoutJsonView.

Then, change TaskJsonView list method.

Continues to Web Application with Kotlin 1.1.61 and Spring (4 of 4).