We will start with creating a service returning a hardcoded string. After that, we will discuss an example returning a proper JSON response. We will also look at an example of passing a path parameter.
Let's start with creating a simple REST service returning a welcome
message:
@RestController class BasicController { @GetMapping("/welcome") fun welcome() = "Hello World" }
A comparable Java method is shown as follows. A major difference is how we are able to define a function in one line in Kotlin--fun welcome() = "Hello World"
:
@GetMapping("/welcome") public String welcome() { return "Hello World"; }
If we run FirstWebServiceWithKotlinApplication.kt
as a Kotlin application, it will start up the embedded Tomcat container. We can launch up the URL (http://localhost:8080/welcome
) in the browser, as shown in the following screenshot: