REST API with SpringBoot (Kotlin / Java)

Sreehari Vasudevan
5 min readJan 4, 2020

--

REST API which are used to connect between different entities in software world , can be created with multiple solutions. This is required to connect different Micro Services / Frontend with Backend / Desktop Solutions with Remote server / Mobile App with Backend etc. I found REST API creation with SpringBoot as much more interesting 😇 With IntelliJ OR Spring Initializer and Spring Tool Suit 💪 💻

Photo by Tim Johnson on Unsplash

Prerequisite: Kotlin / Java. Either way the outcome will be the same.

Full source code can be found in GithubKotlinProject and GithubJavaProject

This article is targeted to explain steps of REST API creation with Kotlin/Java and IntelliJ. So let’s start!

Launch IntelliJ and click on Create New Project.

Select Spring Initialzr , choose Default option as shown and click next.

Give the Group / Artifact / Select Language / Name / Description and Package as per your preference. Click Next button.

Search for Dependency required. And select Spring Web. Selected Dependency will show Spring Web. Click Next.If more dependencies are required, you can search and add over here. If database is required, you can select JPA. Then add Spring Data JPA and other related dependencies as well.Any new dependency required can be added later on in pom.xml. As this Article is intended to explain only creation of REST without any database dependency, I will select only web as of now.

Select required project location. Click Finish.

Expand your source package, src/main/kotlin/package_name. You can see class named SpringbootrestapiktApplication.kt

@SpringBootApplication
class SpringbootrestapiktApplication

fun main(args: Array<String>) {
runApplication<SpringbootrestapiktApplication>(*args)
}

As per Spring docs, this indicates a configuration class that declares one or more @Bean methods and also triggers auto-configuration and component scanning. This is a convenience annotation that is equivalent to declaring @Configuration, @EnableAutoConfiguration and @ComponentScan.

Create a new RestController named StudentResource.java under new folder controllers. Annotate this class with @RestController to indicate this is a controller. Now this class can have different mappings, which can be invoked from outerworld with valid parameters and semantics. 🤔

Basically controller classes are interfaces to outer world which can accept requests. Which in-turn validates the request parameters, process corresponding business logic and get back data with help of other inter related components. 😎

Majorly used request mappings are @GetMapping, @PostMapping, @DeleteMapping, @PutMapping.

@RestController
class StudentResource {

@Autowired
val studentsRepo = StudentsRepo()
}

Create Repository class named StudentsRepo. Annotate this class with @Respository. Ideally this class will have connection to database using JPA. But as this article does not cover database part, we will have local objects to store and manipulate list of objects. We will use Autowired annotation to inject repo dependency using Spring dependency injection facilities.

@Repository
public class StudentsRepo {

var mAllStudents = mutableListOf<Student>()

init {
val s1 = Student("Hari",24,"Student Address 1")
val s2 = Student("Sandy",33,"Student Address 2")
val s3 = Student("Jenny",12,"Student Address 3")

mAllStudents.add(s1)
mAllStudents.add(s2)
mAllStudents.add(s3)
}
}

As shown here, we have pojo class Student. And mAllStudents will be holding all objects manipulated by outer world. For initial response, I have just created sample Student object and added to mAllStudents list. 😊

Now in-order to retrieve all students as a json response, we will create a new method getAllStudents. Annotate with @GetMapping. This will help us in retrieving the targeted data and get back as JSON response.

@GetMapping(“getallstudents”)
fun getAllStudents(): List<Student>{

return studentsRepo.retrieveAllStudents()
}

Corresponding method in Repo class will be the below , which will get back all students data.

fun retrieveAllStudents(): List<Student>{
return mAllStudents
}

In-order to run our Spring project, Click on Run Green button

Our local server will be running in 8080 port, the url will be http://localhost:8080/ . 🧐

To see the port number, verify the port number from console window. As you can see, the port number is 8080. 👀

We can use any rest client to test the response. Postman is widely used popular tool. We can also use Advanced Rest client as well.

As you can see request http://localhost:8080/getallstudents gets back valid JSON response. 💚 👏 🎉

End point showing success response.

For creating new Student , use @PostMapping. Create new method like following. Use RequestBody mapping for accepting JSON object as input. Which will be the Student object in JSON form.

@PostMapping(“/createStudent”)
fun createNewStudent(@RequestBody student:Student): List<Student>{

return studentsRepo.addStudent(student)
}

For demonstration , I am adding the new object to list in Repository class.

In REST client, use Method as POST. Use Request URL as http://localhost:8080/createStudent . For giving input JSON, use Parameters section. Select Body. And give new Student data as input. Click on Send button. You can verify the respose code as 200 💚 👏🥳

POST method for new Student creation.

You can validate the newly created Student with previous End point.Which was this : http://localhost:8080/getallstudents

Similarly you can try out PutMapping , PatchMapping etc.

For demonstrating search and delete, I have created the following in Controller.

  1. Delete functionality using DeleteMapping
  2. Search specific student using GetMapping

Hope you found this article helpful. Thanks for reading. 😇

Full source code can be found in GithubKotlinProject and GithubJavaProject

Do clap if you find this article helpful👏👏

Happy Coding! 🥳 Cheers! 🤜 🤛 🥂

--

--