Create a REST API With Spring Boot

Senura Vihan Jayadeva
7 min readApr 13, 2021

Hello guys, I’m Senura Vihan Jayadeva. In this tutorial, I will guide you to build a RESTful Web Service with Spring Boot.

Right, First of all, let’s see what are our requirements. For this project we need

  • IDE or text editor ( Eclipse , Intellij )
  • JDK 1.8+
  • Maven 3+ or Gradle 4+ (We will be relying on Maven for this article)

In this tutorial, I will be used Intellij as the IDE and MySql as the Database.

Our First step is initializing a Spring Boot Project. For that, I’m going to Intellij IDE. Then go to File -> New -> Project -> Spring Assitant.

If you can see an option called Spring Assitant, first we have to install that plugin.

Go to File->Settings->Plugins

Then install Spring Assistant.

Okay!. I think if you had some problem with spring assistant now it’s clear.

Now As I mentioned earlier go to Spring Assistant and click next.

Then you can specify your own Groud Id, Artifact Id, Project Name, Java Version as you wish. Then click next.

We’ll add a few dependencies here as well, as we’ll want to use them in our project:

  • Spring Web — To include Spring MVC and embedded Tomcat into your project
  • Spring Data JPA — Java Persistence API and Hibernate
  • Spring Boot DevTools — Very useful development tools
  • MySQL Driver — JDBC Driver (Can be any DB you’d like to use)
  • Lombok — Java library tool that generates code for minimizing boilerplate code. The library replaces boilerplate code with easy-to-use annotations

After adding those dependencies click next.

Then you have to select a name for the project and select a project location. After that click on the Finish button to build the project.

After we created the project, if you go to pom.xml you can see the dependencies that we have been installed.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="" xmlns:xsi=""
<relativePath/> <!-- lookup parent from repository -->
<description>Demo project for Spring Boot</description>


<name>Spring Releases</name>
<name>Spring Releases</name>


Connect Spring Boot Application With the database

Next, before we start working on the application, we’ll want to set up the database. This can easily be done through Spring Data JPA, which allows us to set this connection up with just a couple of parameters.

For that under the resources folder, you can see a file called

Inside the file add those details. As I mentioned earlier here we use MySQL as the database. Here we have to specify our database name, username, and password.

spring.datasource.url = jdbc:mysql://localhost:port/databasename
spring.datasource.username = username
spring.datasource.password = password = true
spring.jpa.hibernate.ddl-auto = update = org.hibernate.dialect.MySQL5Dialect

Right, Now we are done with connecting the spring boot application with the database.

Creating a Student Model ( Domain Model )

Now let’s create our student model. First of all, I will create a package for models. Inside the model package, I’m going to create a class call Then add the following code.

package com.example.demo.model;import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
public class Student {
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String name; private int age; private String city;}

Here you don’t have to generate constructors, getters, and setters because those are done by @Data, @AllArgsConstructor, and @NoArgsConstructor annotations which were provided by Lombok dependency.

The @Entity annotation specifies that the class is an entity and is mapped to a database table. The @Table annotation specifies the name of the database table to be used for mapping. The @Id annotation specifies the primary key of an entity and @GeneratedValue provides for the specification of generation strategies for the values of primary keys.

Creating Repository Classes ( Persistence Layer )

Our next step is creating a repository class. @Repository is a Spring annotation that indicates that the decorated class is a repository. A repository is a mechanism for encapsulating storage, retrieval, and search behavior that emulates a collection of objects.

First of all, I’m going to create a package for repository classes. Inside the package create an Interface called StudentRepository. Then add the following code.

package com.example.demo.repository;import com.example.demo.model.Student;
import org.springframework.stereotype.Repository;
public interface StudentRepository extends JpaRepository<Student,Integer> {

Here you can see I extends the interface by JpaRepository and passed the Student Model and data type of its Id.

JpaRepository is JPA specific extension of Repository. It contains the full API of CrudRepository and PagingAndSortingRepository. So it contains API for basic CRUD operations and also API for pagination and sorting.

Creating a Service ( Business Layer )

We mark beans with @Service to indicate that it’s holding the business logic. So there’s not any other specialty except using it in the service layer.

Here we are going to implement the functions like Insert, retrieve, update and delete the Student records. We wrote the business logic in the service class file.

Now create a package called service and under the service package create a class called StudentService. Finally, add the following code inside the StudentService class.

package com.example.demo.service;import com.example.demo.model.Student;
import com.example.demo.repository.StudentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
public class StudentService {
private StudentRepository studentRepository;
public Student addStudent(Student student){
public List<Student> getStudents(){
return studentRepository.findAll();
public Student getStudentById(int id){
return studentRepository.findById(id).orElse(null);
public String deleteStudent(int id){
return "Student removed";
public Student updateStudent(Student student){
Student existingStudent = studentRepository.findById(student.getId()).orElse(null);

Here we @Autowired the StudentRepository and called the methods.

Creating a Controller

The code below shows the Rest Controller class file, here we @Autowired the StudentService class and called the methods for crud operations.

package com.example.demo.controller;import com.example.demo.model.Student;
import com.example.demo.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;@CrossOrigin("*")
@RequestMapping(value = "/api/students")
public class StudentController {
private StudentService studentService;
public Student addStudent(@RequestBody Student student){
return studentService.addStudent(student);
public List<Student> getStudents(){
return studentService.getStudents();
public Student getStudentById(@PathVariable int id){
return studentService.getStudentById(id);
public Student updateStudent(@RequestBody Student student){
return studentService.updateStudent(student);
public String deleteStudent(@PathVariable int id){
return studentService.deleteStudent(id);

Check why I used @CrossOrigin(“*”):

Okay, Now Right-click on the file and click on Run. Before running the application make sure that you have created a database with the name that you have given in the file. In my case demospringboot.

If the application is successfully started you will get an output like below in the console.

Then if you checked the database you can see that the student_table was created.

Right, now we are almost finished. Now we can test the REST APIs using software called Postman.

1.Insert Student Record

2.Get All Students

3.Get Student Details by Id

4.Update Student

5.Delete Student

Okay, This is the end of this spring boot tutorial. Here I covered the basic CRUD operations. Hope today you learned something. Thank you !.



Senura Vihan Jayadeva

Software Engineering undergraduate of Sri Lanka Institute of Information Technology | Physical Science Undergraduate of University of Sri Jayewardenepura