From Zero to Backend: Building a Server-side Application with Spring and Kotlin

Anastasia Ivanova
Hyperskill
Published in
7 min readFeb 8, 2023

Introduction

Welcome to the new series of articles from the Hyperskill Team. It will be devoted to the technical aspects of programming!

In this series, we will take you on a journey of building a backend application from scratch using the Spring framework and the Kotlin programming language. Whether you’re a beginner or an experienced developer in another field, this guide will provide you with the knowledge and skills needed to create a server-side application.

Spring is a popular Java-based framework widely used for building enterprise-level applications. It provides a comprehensive set of features that make it easy to build robust and scalable applications. Kotlin, on the other hand, is a modern, concise, and expressive programming language that is fully compatible with Java. It offers several features that make it an ideal choice for building backend applications.

Throughout this guide, we will cover everything from setting up the development environment to creating a RESTful API, handling database interactions, and deploying the application to a production server. By the end of this series, you will have a solid understanding of how to build a server-side application with Spring and Kotlin. So, let’s get started!

Setting up Environment

Before we begin, you will need to have the following installed on your machine:

  • Java 8 or higher
  • Kotlin
  • IntelliJ IDEA or another IDE
  • Gradle or Maven for building and managing dependencies

Once you have the necessary tools, we can start by creating a new project in your IDE. For this guide, we will use IntelliJ IDEA, but the process should be similar in other IDEs. To create a new project, go to File -> New -> Project and select “Spring Initializer” from the options.

After the project is created, you will need to add the necessary dependencies for the Spring framework. In the build.gradle file, you can add the following dependencies:

  • spring-web
  • spring-data-jpa
  • h2

Or you can use the menu in Intellij to find all these dependencies, like in the screenshot below:

These dependencies will give you the basic functionality for creating the RESTful API and handling database interactions. You can also add other dependencies as needed for your application.

With the development environment set up, we can move on and create the RESTful API for our application.

Getting started with Spring

IntelliJ IDEA created the Spring Boot project for us. To run it, all you have to do is open the main file and run the main function.

The application logs tell us that everything is configured properly, and we can move on!

Creating RESTful API:

Now that we have set up the development environment, we can start building our RESTful API. In this section, we will use the Spring framework to handle the routing and request handling and Kotlin for the API’s logic.

First, we will create a controller class to handle the routing for our API. In the controller class, we will use the @RestController annotation to indicate that this class will handle the RESTful API requests.

@RestController
class TasksController {
//API logic here
}

Next, we will define our API endpoint using the @RequestMapping annotation. This annotation allows us to specify the path at which the endpoint will be accessible. For example, we can create an endpoint for fetching a task’s information using the following code:

@GetMapping("/task/{id}")
fun getTask(@PathVariable id: Long): Task {
//Fetch task with the provided id and return it
}

We can also add other request methods, such as @PostMapping for creating a new resource and @DeleteMapping for deleting an existing resource.

Connecting to Database:

In this section, we will use the Spring Data JPA library to handle database interactions. This library allows us to easily create repositories for interacting with our database and provides a convenient way to define our database schema using Java classes.

First, we will create an entity class that represents our database table. For example, we can create a Task entity as follows:

@Entity
data class Task(
@Id @GeneratedValue
val id: Long,
val name: String,
val description: String,
val complexity: Complexity
)

enum class Complexity {
EASY, MEDIUM, HARD
}

Next, create a repository interface that will handle CRUD operations for our Task entity. You can do it by extending the CrudRepository interface and specifying the entity and primary key types.

interface TaskRepository : CrudRepository<Task, Long>

With the repository set up, we can now use it in our controller to fetch and update data from the database.

Using Repository in Controller:

Now that we have set up our repository, we can use it in our controller to fetch and update data from the database. We can use the @Autowired annotation to inject the repository into our controller.

@Autowired
lateinit var taskRepository: TaskRepository

With the repository injected, you can use it in the API endpoints to fetch and update data. For example, in our getTask endpoint, we can fetch a task by its ID using the findById method provided by the repository.


@GetMapping("/task/{id}")
fun getTask(@PathVariable id: Long): Task {
return taskRepository.findById(id).orElseThrow { TaskNotFoundException(id) }
}

There may not be a task with a given ID. So we need to consider it and create an exception for this case.

class TaskNotFoundException(id: Long) :
Exception("Task with id = $id not found")

Don’t forget that you need to handle exceptions in Spring! For this purpose, there is the so-called ControllerAdvice. ControllerAdvice is a mechanism in Spring that allows developers to centralize the handling of exceptions and apply common behavior to multiple controllers within an application. It provides a way to separate cross-cutting concerns from the business logic, making the code more modular and maintainable.

We will consider the detailed use of the various Spring patterns in the future, but for now, let’s create a simple TaskNotFoundException handler:

@ControllerAdvice
class ControllerAdvice {
@ExceptionHandler
fun handleTaskNotFoundException(ex: TaskNotFoundException): ResponseEntity<ErrorMessage> {
val errorMessage = ErrorMessage(
ex.message, HttpStatus.NOT_FOUND.toString(),
)
return ResponseEntity(errorMessage, HttpStatus.NOT_FOUND)
}
}

Put the appropriate annotations (@ControllerAdvice, @ExceptionHandler) to make everything work in Spring. We also create a special class to return errors:

class ErrorMessage(
var message: String?,
var status: String
)

We can also use the save method to create a task in the database.

@PostMapping("/task")
fun createTask(@RequestBody task: Task): Task {
return taskRepository.save(task)
}

Additionally, we can use the deleteById method to delete a task from the database.

 @DeleteMapping("/task/{id}")
fun deleteTask(@PathVariable id: Long) {
taskRepository.deleteById(id)
}

Let’s try our API with IDEA HTTP files: New ->HTTP Request:

After request execution, we will see the following console response:

Now, let’s try GET localhost:8080/task/1. And we will receive the same output as above.

DELETE localhost:8080/task/1: <Response body is empty>

Again GET localhost:8080/task/1 after deletion:

So everything is going as planned!

With these basic CRUD operations implemented, we have successfully created a simple server-side application using Spring and Kotlin.

Keep in mind that this is just a basic example, and you can use the repository methods and other features that Spring provides to build more complex applications.

Wrapping Up

In conclusion, building a server-side application with Spring and Kotlin is a straightforward process. With Spring’s powerful features and Kotlin’s expressive and concise syntax, you can create robust and maintainable applications. We have covered the basics of setting up a Spring project, creating models, and using repositories to interact with the database. We hope this article has provided you with a solid foundation to build your server-side applications.

If you want to learn more about building server-side applications with Spring and Kotlin, we recommend check out hyperskill.org — an online platform for project-based learning in computer languages, data science, and mathematics.

In collaboration with our main content provider, JetBrains, we offer interactive and comprehensive tracks on Spring and Kotlin, as well as other programming languages and technologies.

Here are the links to some topics where you can continue to learn Spring, with good theory and practical problems and questions:

Also, if you want to study Kotlin, choose our tracks, Kotlin Basics and Kotlin Developer!

If you want to learn courses with high-quality content , personalized curriculum , and engaging practical tasks — welcome to Hyperskilll!

We hope you found it helpful. If you have any questions or feedback, let us know in the comments below. If you enjoyed this article and would like to stay updated on similar content, you’re welcome to subscribe to our newsletter.

You can also follow us on social media to stay up-to-date with our latest articles and projects. We are on Reddit, LinkedIn and Facebook.

Thank you for reading, and happy coding!

--

--