HTTP Endpoint with Kotlin & Spring
**Using Kotlin language and spring web framework, let us build a simple HTTP endpoint.
Setup the Project
- Go to spring initializr
- Pick Gradle as a project, Kotlin as a language and 2.4.0 as a version of Spring Boot.
- Fill project metadata with
- Group com.example
- Artifact and Name as http
- Description as Example HTTP application
- Packaging as JAR
- Java version as 11
- Click on GENERATE button to get a zip file of the project.
- Extract the zip file to get the project.
Understand the project structure
The project has a main class fileHttpApplication.kt
under src/main.kotlin/com/example/http
. It contains the main function fun main
. This is where you could define the steps to start the application.
@SpringBootApplication
class HttpApplication
fun main(args: Array<String>) {
runApplication<HttpApplication>(*args)
}
The project contain two gradle files build.gradle.kts
and settings.gradle.kts
.
build.gradle.kts
define the dependencies required for the project. It also defines the tasks that can be configured for the project. More details building build scripts at Gradle build scripts.
The purpose of thesettings.gradle.kts
is to define all submodules required for the project. It also defines settings like the project root directory. More details at Gradle Settings
Add the web-starer dependency
To build a spring application for HTTP, a new dependency spring-boot-starter-web
is to be added. Go to build.gradle.kts
and under dependencies section add the following:
implementation("org.springframework.boot:spring-boot-starter-web")
Start the project
The project can be started using the command, run in the root folder of the project.
./gradlew bootRun
Create a example controller
Define a new Controller class which can listen to a HTTP request and respond. The controller acts as an interface between external users of HTTP application and the internal services which can process the request. Annotate the controller with @RestController
, indicating to spring that it's a controller class with responses directly appended to response body instead of rendering a HTML template.
Define a HTTP endpoint in the controller
Define a function in the controller which maps a defined route to a function handler. The function is annotated with a @GetMapping
annotation with a route as a parameter. In our case, we map to route/
. The function is a simple function returning a string message as a response.
@RestController
class HtmlController {
@GetMapping(\"/\")
fun hello(): String {
return \"Hello world!\"
}
}
Preview the HTTP endpoint
Run the application using ./gradlew bootRun
and hit http://localhost:8080 in a browser. As it can be seen, the string message returned from the controller's function is displayed in the browser.
Hope the article gave a glimpse of how to define a HTTP endpoint using Spring & Kotlin and serve it to end-user. The code is available at Github.