NashTech Insights

Building RESTful API with Spring Boot: Kotlin

Harsh Vardhan
Harsh Vardhan
Table of Contents
ai generated, data centre, computer-8070003.jpg

What is Kotlin?

Kotlin is a high-level object-oriented programming language developed by JetBrains in 2011. It is used to develop especially Android apps and server-side apps. It runs on JVM(Java Virtual Machine). To learn more about Kotlin click here

Prerequisite

  • Basic knowledge of Kotlin.
  • Familiar with Spring Boot.
  • Familiar with Gradle build tools.

Scope of this article

  • Create a RESTful Spring Boot Application and perform CRUD (Create, Read, Update, and Delete) Operation.
  • Consider MySQL for the database.
  • Swagger for API documentation.
  • SonarQube: Enhancing Code Quality and Maintenance.
  • Spring Security.

What is Spring Boot?

Spring Boot is an open-source framework that simplifies the development of Spring-based applications. It is based on the Spring framework and offers a streamlined and thoughtful approach to building production-ready applications quickly and easily. It is an excellent choice for building modern, scalable, and maintainable applications.

Spring Vs Spring Boot

AspectSpringSpring Boot
PurposeIn Kotlin, Spring is still a comprehensive framework for building enterprise-level Java applications. However, thanks to Kotlins’ interoperability with Java, developers can seamlessly use Springs functions and modules in Kotlin-based projects.Kotlin works just as well with Spring Boot, and developers can take advantage of Spring Boots’ idiosyncratic approach to easily build and deploy Kotlin-based applications.
ConfigurationKotlin provides expressive and concise syntax, making Spring configuration code more concise and readable compared to Java. Developers can use Kotlin’s DSL (Domain-Specific Language) to define beans and configurations.Spring Boots’ auto-configuration feature works seamlessly with Kotlin. Developers can use Kotlins syntax to override default configurations or define custom configurations.
Starter DependenciesIn Kotlin-based Spring applications, developers can use the same starter dependencies as in Java. Kotlins interoperability allows for a seamless experience with Springs’ existing libraries and modules.Kotlin’s null-safety and type inference features work well with Spring Boots starter dependencies. Developers can include Starters in their Kotlin projects and easily benefit from the pre-built dependencies.
Embedded ServersKotlin-based Spring applications can be deployed to external servers just like Java-based Spring applications.Kotlin-based Spring applications can be deployed to external servers just like Java-based Spring applications (Jetty, Tomcat).
Project StructureKotlin does not dictate a specific project structure for Spring applications. Developers have the freedom to structure their projects, however, they wish.The predefined project structure provided by Spring Boot is equally applicable to Kotlin projects. Developers can use this structure to effectively organize their Kotlin-based Spring Boot projects
Ease of UseKotlin’s concise syntax and null-safety features can result in more concise and robust Spring configurations, making development more efficient and error-resistant.Kotlin interoperability with Spring Boot allows developers to enjoy the same convenience and ease of use that Spring Boot offers Java developers.

Let’s get started, Create a Spring Boot application from this link or from your InteliJIDEA: https://start.spring.io/

I have added the necessary dependencies as per my application requirements after generating it, the zip file will be downloaded and then extract and open it with your IDE. IntelliJIDEA will be utilized for this application.

Adding MySQL database configuration

Dependency for MySQL Driver has been added already as you can see in the above image as well.

Add this code to the application.properties file inside the src/main/resource folder.
spring.datasource.url = jdbc:mysql://localhost:3306/KotlinWithSpringBootBlogs

spring.datasource.driver-class-name = com.mysql.cj.jdbc.Driver

spring.datasource.username=your_Mysql_username

spring.datasource.password=your_MySQL_Password

spring.jpa.properties..hibernate.dialect = org.hibernate.dialect.MySQLDialect

spring.jpa.hibernate.ddl-auto=update

spring.jpa.show-sql=true

spring.jpa.properties.hibernate.format_sql=true

Now let’s create a Controller class that is responsible for handling incoming HTTP requests from clients (such as web browsers, mobile devices, or APIs) and returning an appropriate HTTP response. It acts as an intermediary between the client and the application’s business logic and data.

Create an API Endpoint

@RestController

@RequestMapping("api/employees")

class EmployeeController(private val employeeService: EmployeeService) {

 @GetMapping("/greet")

  fun greet() : String {

      return "Hello Rishika!!!"

    }

}

@RestController is a Spring Framework annotation used to mark a class as a RESTful web service controller. It allows the class to handle HTTP requests and generate HTTP responses for building RESTful APIs.

Get Operation or @GetMapping

@GetMapping annotation is used to handle incoming HTTP GET requests on a specific URL or endpoint. It is a shortcut for specifying a handler method that will be invoked when a client sends an HTTP GET request to the defined URL.

Example:

@GetMapping

   fun findAllEmployee(): List<Employee> {

  return employeeService.findAllEmployee()

    }

To obtain specific data, the GetMapping is employed. In this instance, it is used to retrieve the data of a single employee based on their ID. Let’s take a look:

Example:

@GetMapping("/{id}")

fun findEmployeeById(@PathVariable("id") id: Long): Optional<Employee> {

 return employeeService.findById(id)

    }

Post operation or @PostMapping

The @PostMapping annotation is part of the Springs package org.springframework.web.bind.annotation and is used at the method level within a Spring controller. It specifies that the annotated method should process HTTP POST requests sent to the specified URL mapping. When a POST request is made to the specified URL, Spring calls the method annotated with @PostMapping and the method processes the request and generates a response.

Example:

@PostMapping

fun saveEmployee(@RequestBody employeeEntity: Employee): Employee {

return employeeService.saveEmployee(employeeEntity)

    }

Put Operation or @PutMapping

The @PutMapping annotation is part of the Springs package org.springframework.web.bind.annotation and is used at the method level within a Spring controller. It specifies that the annotated method should handle HTTP PUT requests sent to the specified URL mapping. When a PUT request is made to the specified URL, Spring calls the method annotated with @PutMapping and the method handles the request and generates a response.

The @PutMapping annotation is commonly used in RESTful API development where PUT requests are used to update resources on the server. Unlike a POST request, which is used to create new resources, a PUT request is used to modify an existing resource or update its status.

Example:

@PutMapping("/{id}")

fun updateEmployee(@PathVariable ("id") id: Long, @RequestBody employeeEntity: Employee): Employee {

return employeeService.updateEmployee(employeeEntity)

    }

Delete Operation or @DeleteMapping

The @DeleteMapping annotation is part of the Springs package org.springframework.web.bind.annotation and is used at the method level within a Spring controller. It indicates that the annotated method should handle HTTP DELETE requests sent to the specified URL mapping. When a DELETE request is made to the specified URL, Spring calls the method annotated with @DeleteMapping and the method processes the request and generates a response.

The @DeleteMapping annotation is commonly used in RESTful API development where DELETE requests are used to remove or delete a resource from the server.

Example:

@DeleteMapping("/{id}")

fun deleteEmployee(@PathVariable("id") id: Long) {

   employeeService.deleteEmployee(id)

    }

Implementation of Swagger

Swagger, now known as OpenAPI, is an open-source framework that allows developers to design, document, and interact with RESTful APIs. It provides a standardized and machine-readable way to describe APIs, enabling easy use and integration of APIs by customers and developers.

Swagger allows developers to create comprehensive and interactive documentation for their APIs. With Swagger, you can describe the endpoints, request, and response parameters, data types, and error codes in a structured way. This documentation is useful for both internal and external developers to understand how to interact with the API without having to examine the source code.

Add the following dependency in your build. gradle file:

implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.1.0'

package com.knoldus.kotlin.api_documentations

import io.swagger.v3.oas.annotations.OpenAPIDefinition

import io.swagger.v3.oas.annotations.info.Contact

import io.swagger.v3.oas.annotations.info.Info

import io.swagger.v3.oas.annotations.info.License

import org.springframework.context.annotation.Configuration

@Configuration

@OpenAPIDefinition(info =

Info(

    title = "Spring Boot Using Kotlin",

    version = "2.1.0",

    termsOfService = "CRUD operations",

    license = License(url = "https://www.google.com/search?channel=fs&client=ubuntu&q=knoldus+inc", name = "KnoldusInc"),

    contact = Contact(name = "Rishika Kumari", email = "rishika.kumari@knoldus.com")

)

)

class SwaggerConfig

Let’s see how Swagger used to document our APIs

Note: Endpoints can be accessed via POSTMAN as well.

Implementation of SonarQube

SonarQube is an open-source platform developed by SonarSource that provides continuous code quality management for software projects. It is commonly used by development teams to automatically analyze and measure the quality of their code base. SonarQube can analyze code written in various programming languages ​​including Java, C/C++, C#, Python, JavaScript, TypeScript, and more.

SonarQube performs a static code analysis of the source code to identify potential bugs, vulnerabilities, and code odors. It uses various rules and algorithms to detect problems and provides detailed reports on the state of the code base.

Bug and vulnerability detection: SonarQube can find potential bugs and vulnerabilities in code. It can detect common coding errors and security vulnerabilities like SQL injection, cross-site scripting (XSS), and more.

Code Coverage: SonarQube can analyze test coverage to determine how much of the code is covered by unit tests. This helps developers ensure that their tests are thorough and that critical parts of the code are adequately tested.

Implementation Spring Security

Spring Security is a comprehensive security framework that provides authentication, authorization, and various security features to protect web applications and RESTful APIs. It seamlessly integrates with Spring Boot applications and provides a robust and flexible way to secure endpoints, control access to resources, and manage user authentication.

When building a Spring Boot application, you can easily add Spring Security to your project by including the spring-boot-starter-security dependency. This launcher brings with it all the necessary configurations and dependencies to enable Spring Security in your application. By default, Spring Security secures your application by requiring HTTP Basic authentication for all requests.

Add the following dependency for spring – security:

implementation’org.springframework.boot:spring-boot-starter-security’

After implementing the Spring Security, you will see a login page the username is by default “user” and the password for that will be displayed on the console once you run the application.

Conclusion

This Kotlin with Spring Boot blog series explored the powerful combination of these technologies to create robust and efficient web applications.Through the integration of Swagger, rich API documentation and interactive testing capabilities have been achieved. This enhancement simplifies developers’ understanding and interaction with the endpoints.The addition of SonarQube allowed us to continually monitor and improve code quality, ensuring a maintainable and secure code base. Furthermore, using MySQL for our CRUD application demonstrated the seamless integration of a reliable and scalable database solution. Finally, implementing the basic functionality of Spring Security allowed us to secure our application, control access to resources and effectively manage user authentication. Therefore, this blog series provides a solid foundation for developers to unlock the full potential of Kotlin and Spring Boot when building high-quality, secure, and feature-rich web applications.

Reference

The real author of the blog is Rishika Kumari you can find her blog here. Click here!

Harsh Vardhan

Harsh Vardhan

Leave a Comment

Your email address will not be published. Required fields are marked *

Suggested Article

%d bloggers like this: