Building a Simple REST API with Spring Boot and Kotlin

  • 2024/11/11
  • Building a Simple REST API with Spring Boot and Kotlin はコメントを受け付けていません

Introduction

Spring Boot is a popular framework for building Java-based applications, offering a fast and easy way to set up, develop, and deploy applications. When combined with Kotlin, a modern, concise, and safe language, developers can create clean, efficient, and readable code. In this article, we’ll walk through building a simple REST API using Spring Boot and Kotlin to manage a list of books.

Setting Up the Project

Before we begin, ensure that you have the following prerequisites installed:

  • JDK 17 
  • IntelliJ IDEA (or any other preferred IDE)
  • Gradle or Maven

Creating a New Spring Boot Project

  1. Using Spring Initializr:
    • Visit the Spring Initializr website.
    • Set the project parameters:
      • Project: Gradle Project (or Maven)
      • Language: Kotlin
      • Spring Boot: Latest stable version
      • Group: com.example
      • Artifact: bookstore
    • Add the following dependencies:
      • Spring Web: To build web applications, including RESTful services.
      • Spring Data JPA: To simplify database access.
      • H2 Database: An in-memory database for simplicity.
    • Click Generate to download the project.
  2. Unzip the downloaded project and open it in your IDE.

Creating the Book Entity

We’ll start by creating a simple data model for our application. A book entity will have three properties: id, title, and author.

package com.example.bookstore.model

 

import javax.persistence.Entity
import javax.persistence.GeneratedValue
import javax.persistence.GenerationType
import javax.persistence.Id

@Entity
data class Book(
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
val id: Long = 0,
val title: String,
val author: String
)

Setting Up the Repository

The repository interface will handle CRUD operations for our book entity. Spring Data JPA provides a JpaRepository that we can extend to get these operations out of the box.

package com.example.bookstore.repository

import com.example.bookstore.model.Book
import org.springframework.data.jpa.repository.JpaRepository

interface BookRepository : JpaRepository<Book, Long>

Creating the Service Layer

The service layer will contain the business logic of our application. It will interact with the repository to perform operations on the book data.

package com.example.bookstore.service

import com.example.bookstore.model.Book
import com.example.bookstore.repository.BookRepository
import org.springframework.stereotype.Service

@Service
class BookService(private val bookRepository: BookRepository) {

fun getAllBooks(): List<Book> = bookRepository.findAll()

fun addBook(book: Book): Book = bookRepository.save(book)
}

Building the REST Controller

Next, we’ll create a REST controller to expose our API endpoints for interacting with books. We’ll create two endpoints:

  • GET /books: To retrieve a list of all books.
  • POST /books: To add a new book to the list.
package com.example.bookstore.controller

import com.example.bookstore.model.Book
import com.example.bookstore.service.BookService
import org.springframework.http.HttpStatus
import org.springframework.web.bind.annotation.*

@RestController
@RequestMapping(“/books”)
class BookController(private val bookService: BookService) {

@GetMapping
fun getAllBooks(): List<Book> = bookService.getAllBooks()

@PostMapping
@ResponseStatus(HttpStatus.CREATED)
fun addBook(@RequestBody book: Book): Book = bookService.addBook(book)
}

Configuration for Database

For simplicity, we’re using the H2 in-memory database, which requires minimal configuration. Add the following to your application.properties file:

spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=password
spring.h2.console.enabled=true
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.jpa.hibernate.ddl-auto=update

Running the Application

To run the application:

  1. Navigate to the main application file, BookstoreApplication.kt.
package com.example.bookstore

import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication

@SpringBootApplication
class BookstoreApplication

fun main(args: Array<String>) {
runApplication<BookstoreApplication>(*args)
}
  1. Run the application using your IDE’s run button or execute ./gradlew bootRun (or ./mvnw spring-boot:run for Maven) in the terminal.

Testing the Endpoints

With the application running, you can test the endpoints using a tool like Postman or curl.

  1. GET /books: This should return an empty list initially.
curl -X GET http://localhost:8080/books

 

  1.   POST /books: Add a new book to the list.
curl -X POST http://localhost:8080/books \
-H “Content-Type: application/json” \
-d ‘{“title”: “Kotlin for Beginners”, “author”: “Jane Doe”}’

 

  1.     GET /books: This should now return the newly added book.
    bash
curl -X GET http://localhost:8080/books

 

Conclusion

By combining Spring Boot with Kotlin, we’ve created a straightforward REST API for managing a list of books. This example demonstrates the simplicity and effectiveness of using Kotlin for developing Spring Boot applications, leveraging Kotlin’s concise syntax and Spring Boot’s powerful capabilities.

The same approach can be expanded to more complex scenarios, such as handling additional CRUD operations, integrating with different databases, or adding more sophisticated business logic. With this foundation, you’re well on your way to building robust, scalable web services using Spring Boot and Kotlin.

関連記事

カテゴリー:

ブログ

情シス求人

  1. チームメンバーで作字やってみた#1

ページ上部へ戻る