Spring Boot Rest APIs using Kotlin and MongoDB

Kotlin is a programming language primarily developed to be used by JetBrains for their product IntelliJ Idea and in 2019 Google announced that it will be the preferred language for Android development. Since then Kotlin has been replacing Java, now on the server side also. Because of its concise nature, null safety, data classes, extensions, coroutines more and more developers are now switching to it.

As per a survey conducted last conducted in 2019, 41% of kotlin apps were Web Back-end.

Kotlin 2019 — The state of Developer Ecosystem in 2019

Now in this tutorial, we will use it on the server-side and will create some basic Rest APIs using the popular Spring Boot framework and MongoDB Database

Step 1 — Spring initializr

Go to the website https://start.spring.io/ and select kotlin language, for this project I will be using Gradle for project building you can choose Maven also.

Add the two dependencies Spring Web and Spring Data MongoDB. Click on Generate to download the skeleton project.

Spring Initializr tool

Unzip the downloaded project and open in it Intellij Idea.

So We will be creating basic CRUD APIs for an Entity Book. We will add a new book, update its price, fetch all added books, fetch a single book by its ID, and also an endpoint to delete a book by its Id.

So, let's Get Started…

Step2 — Entity

Create a data class named Book and anotate it with @Document annotation, it will create a document in MongoDB database by mapping the class members.
@JsonSerialize — Converts ObjectId to String while fetching

@Id — Will be used as an identifier by MongoDB

@Document
data class Book (

@JsonSerialize(using = ToStringSerializer::class)
@Id
val _id : ObjectId =ObjectId.get(),

var bookTitle : String,
var bookAuthor : String,
var bookMrp : Double,
val createdDate: LocalDateTime = LocalDateTime.now(),
val modifiedDate: LocalDateTime = LocalDateTime.now())

That's all we have to do for MongoDb data modeling

Step 3 — Repository

Repositories handle all the data related operations and you really don’t have to do much here just paste the below code and we are all done

interface BookRepository :MongoRepository<Book,String>{
}

Just create an interface named BookRepository, here the MongoRepository interface provides all the basic methods for CRUD operation. You can also declare methods here called query Method, they are provided by Spring Data JPA.

Step 4 — Controller

In the controller, we will declare the URL endpoints and it will connect to the repository and will perform the operation. For a Real-world project, we will have to add a Service layer also, but here for simplicity, we can skip that.

To Create a controller Create a class named BookController and annotate it with @RestController annotation.

@RestController
class BookController(private val bookRepository: BookRepository) {

Also, instead of using @Autowired as we used to do in Java, we will simply add BookReposity to the constructor.

Let's create our first Endpoint which will Add a book

@PostMapping("/book/add")
fun addBook(@RequestBody bookRequest: CreateBookRequest): ResponseEntity<Book> {
return ResponseEntity.ok().body(bookRepository.insert(Book(
bookAuthor = bookRequest.bookAuthor,
bookMrp = bookRequest.bookMrp,
bookTitle = bookRequest.bookTitle
)))
}

@PostMapping → Used to declare the API s HTTP Method type
@RequestBody → Get the content passed in the request Body
bookRepository.insert → Method provided by MongoRepository that we implemented in our BookRepository

Create Book

Get a Book by its ID

@GetMapping("/book/{id}")
fun getBookDetailsById(@PathVariable("id") bookId : String): ResponseEntity<Book> {
val book = bookRepository.findById(bookId)
if(book.isEmpty) return ResponseEntity.noContent().build()

return ResponseEntity.ok().body(book.get())
}

Get All Books

@GetMapping("/books")
fun getAllPatients(): ResponseEntity<List<Book>> {
return ResponseEntity.ok(bookRepository.findAll())
}

Update Book Content

@PutMapping("/book")
fun updateBook(@RequestBody bookRequest: CreateBookRequest): ResponseEntity<Book> {
if(bookRequest._id==null) return ResponseEntity.badRequest().body(null)

val bookToUpdate = bookRepository.findById(bookRequest._id)

if(bookToUpdate.isEmpty) return ResponseEntity.noContent().build()

bookToUpdate.get().apply {
this.bookAuthor = bookRequest.bookAuthor
this.bookMrp = bookRequest.bookMrp
this.bookTitle = bookRequest.bookTitle
}
return ResponseEntity.ok().body(bookRepository.save(bookToUpdate.get()))
}

Delete Book by Its ID

@DeleteMapping("/book/{id}")
fun deleteBook(@PathVariable("id") bookId : String): ResponseEntity<Book> {
bookRepository.deleteById(bookId)
return ResponseEntity.ok().body(null)
}

For testing, you can also use In Memory version of the MongoDb database.

Mongo DB Compass

You can clone the project from Github and create your own REST APIs.

That's all Folks

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

CS371p Spring 2022: Vincent Huynh

CS373 Fall 2021: Katelyn Ashok

ClearScore Tech Radar 2021

Previse — Hackthebox walkthrough

Importing RDFS/OWL ontologies into Neo4j

Flutter Day — Recap

Deploy Wordpress Over AWS EC2 using RDS DataBase.

Toolchain and Internals, Internal Representation In PROLOG

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Deepak

Deepak

More from Medium

Eureka Server and API gateway

Spring boot with Mongo DB easy setup

Validating MongoDB Documents in Spring Boot

A MongoDB collection with a basic JSON schema

Spring Batch Admin in Spring Boot 2