Create a RESTful web service with a database using Spring Boot – tutorial
This tutorial walks you through the process of creating a simple application with Spring Boot and adding a database to store the information.
In this tutorial, you will:
Create an application with an HTTP endpoint
Learn how to return a data objects list in the JSON format
Create a database for storing objects
Use endpoints for writing and retrieving database objects
You can download and explore the completed project or watch a video of this tutorial:
Before you start
Download and install the latest version of IntelliJ IDEA.
Bootstrap the project
Use Spring Initializr to create a new project:
-
Open Spring Initializr. This link opens the page with the project settings for this tutorial already filled in. This project uses Gradle, Kotlin, Spring Web, Spring Data JDBC, and H2 Database:
Click GENERATE at the bottom of the screen. Spring Initializr will generate the project with the specified settings. The download starts automatically.
-
Unpack the .zip file and open it in IntelliJ IDEA.
The project has the following structure:
There are packages and classes under the
main/kotlin
folder that belong to the application. The entry point to the application is themain()
method of theDemoApplication.kt
file.
Explore the project build file
Open the build.gradle.kts
file.
This is the Gradle Kotlin build script, which contains a list of the dependencies required for the application.
The Gradle file is standard for Spring Boot, but it also contains necessary Kotlin dependencies, including the kotlin-spring Gradle plugin.
Explore the Spring Boot application
Open the DemoApplication.kt
file:
package demo import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.boot.runApplication @SpringBootApplication class DemoApplication fun main(args: Array<String>) { runApplication<DemoApplication>(*args) }
Note that the Kotlin application file differs from a Java application file:
While Spring Boot looks for a public static
main()
method, the Kotlin application uses a top-level function defined outsideDemoApplication
class.The
DemoApplication
class is not declared asopen
, since the kotlin-spring plugin does that automatically.
Create a data class and a controller
To create an endpoint, add a data class and a controller to your project:
-
In the
DemoApplication.kt
file, create aMessage
data class with two properties:id
andtext
:data class Message(val id: String?, val text: String)
-
In the same file, create a
MessageResource
class which will serve the requests and return a JSON document containing a collection ofMessage
objects:@RestController class MessageResource { @GetMapping fun index(): List<Message> = listOf( Message("1", "Hello!"), Message("2", "Bonjour!"), Message("3", "Privet!"), ) }
Full code of the DemoApplication.kt
:
package demo import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.boot.runApplication import org.springframework.data.annotation.Id import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.RestController @SpringBootApplication class DemoApplication fun main(args: Array<String>) { runApplication<DemoApplication>(*args) } @RestController class MessageResource { @GetMapping fun index(): List<Message> = listOf( Message("1", "Hello!"), Message("2", "Bonjour!"), Message("3", "Privet!"), ) } data class Message(val id: String?, val text: String)
Run the application
The application is now ready to run:
-
Click the green Run icon in the gutter beside the
main()
method or use the Alt+Enter shortcut to invoke the launch menu in IntelliJ IDEA: -
Once the application starts, open the following URL: http://localhost:8080.
You will see a page with a collection of messages in JSON format:
Add database support
To use a database in your application, first create two endpoints: one for saving messages and one for retrieving them:
-
Add the
@Table
annotation to theMessage
class to declare mapping to a database table. Add the@Id
annotation before theid
field. These annotations also require additional imports:import org.springframework.data.annotation.Id import org.springframework.data.relational.core.mapping.Table @Table("MESSAGES") data class Message(@Id val id: String?, val text: String)
-
Use the Spring Data Repository API to access the database:
import org.springframework.data.jdbc.repository.query.Query import org.springframework.data.repository.CrudRepository interface MessageRepository : CrudRepository<Message, String>{ @Query("select * from messages") fun findMessages(): List<Message> }
When you call the
findMessages()
method on an instance ofMessageRepository
, it will execute the corresponding database query:select * from messages
This query retrieves a list of all
Message
objects in the database table. -
Create the
MessageService
class:import org.springframework.stereotype.Service @Service class MessageService(val db: MessageRepository) { fun findMessages(): List<Message> = db.findMessages() fun post(message: Message){ db.save(message) } }
This class contains two methods:
post()
for writing a newMessage
object to the databasefindMessages()
for getting all the messages from the database
-
Update the
MessageResource
class:import org.springframework.web.bind.annotation.RequestBody import org.springframework.web.bind.annotation.PostMapping @RestController class MessageResource(val service: MessageService) { @GetMapping fun index(): List<Message> = service.findMessages() @PostMapping fun post(@RequestBody message: Message) { service.post(message) } }
Now it uses
MessageService
to work with the database.
Configure the database
Configure the database in the application:
-
Create a new folder called
sql
in thesrc/main/resources
with theschema.sql
file inside. It will store the database scheme: -
Update the
src/main/resources/sql/schema.sql
file with the following code:CREATE TABLE IF NOT EXISTS messages ( id VARCHAR(60) DEFAULT RANDOM_UUID() PRIMARY KEY, text VARCHAR NOT NULL );
It creates the
messages
table with two fields:id
andtext
. The table structure matches the structure of theMessage
class. -
Open the
application.properties
file located in thesrc/main/resources
folder and add the following application properties:spring.datasource.driver-class-name=org.h2.Driver spring.datasource.url=jdbc:h2:file:./data/testdb spring.datasource.username=sa spring.datasource.password=password spring.datasource.schema=classpath:sql/schema.sql spring.datasource.initialization-mode=always
These settings enable the database for the Spring Boot application. See the full list of common application properties in the Spring documentation.
Execute HTTP requests
You should use an HTTP client to work with previously created endpoints. In IntelliJ IDEA, you can use the embedded HTTP client:
Run the application. Once the application is up and running, you can execute POST requests to store messages in the database.
-
Create the
requests.http
file and add the following HTTP requests:### Post 'Hello!" POST http://localhost:8080/ Content-Type: application/json { "text": "Hello!" } ### Post "Bonjour!" POST http://localhost:8080/ Content-Type: application/json { "text": "Bonjour!" } ### Post "Privet!" POST http://localhost:8080/ Content-Type: application/json { "text": "Privet!" } ### Get all the messages GET http://localhost:8080/
-
Execute all POST requests. Use the green Run icon in the gutter next to the request declaration. These requests write the text messages to the database.
-
Execute the GET request and see the result in the Run tool window:
Alternative way to execute requests
You can also use any other HTTP client or cURL command-line tool. For example, you can run the following commands in the terminal to get the same result:
curl -X POST --location "http://localhost:8080" -H "Content-Type: application/json" -d "{ \"text\": \"Hello!\" }" curl -X POST --location "http://localhost:8080" -H "Content-Type: application/json" -d "{ \"text\": \"Bonjour!\" }" curl -X POST --location "http://localhost:8080" -H "Content-Type: application/json" -d "{ \"text\": \"Privet!\" }" curl -X GET --location "http://localhost:8080"
What's next?
For more tutorials, check out the Spring website:
© 2010–2021 JetBrains s.r.o. and Kotlin Programming Language contributors
Licensed under the Apache License, Version 2.0.
https://kotlinlang.org/docs/jvm-spring-boot-restful.html