If you are just stating learning server side development / Backend development I strongly suggest you to use Kotlin with Spring Boot.This article will cover your following questions:
Make sure you do not override groupdId. (replace groupdId with your project group id)
group 'com.developine' version '1.0-SNAPSHOT' buildscript { ext.kotlin_version = '1.2.30' // Required for Kotlin integration ext.spring_boot_version = '1.5.4.RELEASE' repositories { mavenCentral() jcenter() } dependencies { classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" // Required for Kotlin integration classpath "org.jetbrains.kotlin:kotlin-allopen:$kotlin_version" classpath "org.springframework.boot:spring-boot-gradle-plugin:$spring_boot_version" } } apply plugin: 'kotlin' apply plugin: "kotlin-spring" apply plugin: 'org.springframework.boot' repositories { mavenCentral() } dependencies { compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" compile 'org.springframework.boot:spring-boot-starter-web' } compileKotlin { kotlinOptions.jvmTarget = "1.8" } compileTestKotlin { kotlinOptions.jvmTarget = "1.8" }
package restapi import org.springframework.boot.SpringApplication import org.springframework.boot.autoconfigure.SpringBootApplication @SpringBootApplication class ApplicationClass { } fun main(args: Array) { SpringApplication.run(ApplicationClass::class.java, *args) }
We will use MYSQL Database.…………………………
In this tutorial, we will create a Restful web service using spring boot in Kotlin. we will also set up MySQL database in our project.
I assume you have the basic understanding of Kotlin, Spring Boot, Restful Web Services, MySQL database, Gradle.
I am using Intellij Idea for development.
group 'com.titleapps' version '1.0-SNAPSHOT' buildscript { ext.kotlin_version = '1.1.4-3' // Required for Kotlin integration ext.spring_boot_version = '1.5.4.RELEASE' repositories { mavenCentral() jcenter() } dependencies { classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" // Required for Kotlin integration classpath "org.jetbrains.kotlin:kotlin-allopen:$kotlin_version" // See https://kotlinlang.org/docs/reference/compiler-plugins.html#kotlin-spring-compiler-plugin classpath "org.springframework.boot:spring-boot-gradle-plugin:$spring_boot_version" } } apply plugin: 'kotlin' apply plugin: "kotlin-spring" // See https://kotlinlang.org/docs/reference/compiler-plugins.html#kotlin-spring-compiler-plugin apply plugin: 'org.springframework.boot' repositories { mavenCentral() } dependencies { compile "org.jetbrains.kotlin:kotlin-stdlib-jre8:$kotlin_version" compile 'org.springframework.boot:spring-boot-starter-web' // JPA Data (We are going to use Repositories, Entities, Hibernate, etc...) compile 'org.springframework.boot:spring-boot-starter-data-jpa' // Use MySQL Connector-J compile 'mysql:mysql-connector-java' } compileKotlin { kotlinOptions.jvmTarget = "1.8" } compileTestKotlin { kotlinOptions.jvmTarget = "1.8" }
First create a new package inside main. “restapi” in this case.
Than create an Application class. which be responsible to start our project.
Add this code in Application class. Note: Application class will not be inside any package. it will be in root package.
package restapi import org.springframework.boot.SpringApplication import org.springframework.boot.autoconfigure.SpringBootApplication @SpringBootApplication class Application { } fun main(args: Array) { SpringApplication.run(Application::class.java, *args) }
Above Application.kt class will start everything including embedded web server.
Now we will add a controller class inside controller package. controller class will know how to handle web requests.
We will develop three rest web services in this project.
For above three API’s we need to define Entity classes. which will be converted automatically into a Table.
import javax.persistence.Entity import javax.persistence.GenerationType import javax.persistence.GeneratedValue; import javax.persistence.Id @Entity class User() { @Id @GeneratedValue(strategy = GenerationType.AUTO) val id: Int? = 0 lateinit var name: String lateinit var email: String constructor(name: String, email: String) : this() { this.name = name this.email = email } }
user id is autogenerated. note @Entity annotation.
Now UserFeed class
import javax.persistence.Entity import javax.persistence.GeneratedValue import javax.persistence.GenerationType import javax.persistence.Id @Entity class UserFeedback() { @Id @GeneratedValue(strategy = GenerationType.AUTO) val id: Int? = 0 lateinit var email: String lateinit var stars: String lateinit var feedback: String lateinit var fcm_token: String lateinit var deviceId: String constructor(email: String, stars: String, feedback: String, fcm_token: String, deviceId: String) : this() { this.email = email this.deviceId = deviceId this.fcm_token = fcm_token this.feedback = feedback this.stars = stars } }
Now create a Repository interface which will handle CRUD.
import org.springframework.data.repository.CrudRepository import restapi.model.User interface UserRepository : CrudRepository{ }
Above interface will be automatically implemented by a bean, and you can call its utility methods from your controller class.
Now we will add controller class. As I mentioned earlier controller class is responsible to accept and handle API requests.
@RestController // means this is controller class @RequestMapping("/api/v1") //url starts with /api/v1 after app path class RestApiController { // To get the bean named userRepository @Autowired lateinit var userRepo: UserRepository // Add new user in DATABASE API. @GetMapping(path = arrayOf("/add")) // Map ONLY GET Requests @ResponseBody fun addNewUser(@RequestParam name: String, @RequestParam email: String): String { if (name == "" || email == "") { // Exception handling explained at the end of this class. throw IllegalArgumentException("invalid input.") } else { val n = User(name, email) n.name = name n.email = email userRepo.save(n) return "Saved" } }
@GetMapping("/users/getuser") fun getAllUsersFromDb(): Any { return userRepo.findAll() }
// ADD BELOW CODE IN YOUR CONTROLLER CLASS FOR EXCEPTION HANDLING in Spring Boot. // YOU CAN ADD MULTIPLE METHODS FOR HANDLING DIFFERENT TYPES OF // EXCEPTION IN YOUR SPRING BOOT PROJECT.
@ExceptionHandler(IllegalArgumentException::class) @ResponseStatus(HttpStatus.BAD_REQUEST) fun handleIllegalArgumentError(e: IllegalArgumentException) = e.message }
Now last thing is create a new resource file in resources folder. and name it application. and add this in application.properties file.
spring.jpa.hibernate.ddl-auto=create spring.datasource.url=jdbc:mysql://localhost:3306/database_name spring.datasource.username=root spring.datasource.password=
Before this make sure you have created database. you can use SQLyog for this purpose.
https://github.com/hammad-tariq/kotlin-spring-boot-resful-mysql-demoCongrats!
You have learned how to create a restful web service in Kotlin using spring boot. and How to setup database in your spring boot project. If you’re planning on using these web services and the database for any reason, you may want to look into api testing services to ensure your newly built API is running how it should be.
Recommended Reading:- Kotlin Idioms Tutorial Kotlin for iOS Application DevelopmentIf you have any confusion/feedback please write in comments section. Thank you.