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="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.4</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>11</java.version>
<spring-native.version>0.9.1</spring-native.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
<image>
<builder>paketobuildpacks/builder:tiny</builder>
<env>
<BP_NATIVE_IMAGE>true</BP_NATIVE_IMAGE>
</env>
</image>
</configuration>
</plugin>

</plugins>
</build>
<repositories>
<repository>
<id>spring-releases</id>
<name>Spring Releases</name>
<url>https://repo.spring.io/release</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-releases</id>
<name>Spring Releases</name>
<url>https://repo.spring.io/release</url>
</pluginRepository>
</pluginRepositories>

</project>

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 application.properties.

Inside the application.properties 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.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url = jdbc:mysql://localhost:port/databasename
spring.datasource.username = username
spring.datasource.password = password
spring.jpa.show-sql = true
spring.jpa.hibernate.ddl-auto = update
spring.jpa.properties.hibernate.dialect = 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 Student.java. Then add the following code.

package com.example.demo.model;import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name="student_tbl")
public class Student {
@Id
@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.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@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;
@Service
public class StudentService {
@Autowired
private StudentRepository studentRepository;
public Student addStudent(Student student){
return studentRepository.save(student);
}
public List<Student> getStudents(){
return studentRepository.findAll();
}
public Student getStudentById(int id){
return studentRepository.findById(id).orElse(null);
}
public String deleteStudent(int id){
studentRepository.deleteById(id);
return "Student removed";
}
public Student updateStudent(Student student){
Student existingStudent = studentRepository.findById(student.getId()).orElse(null);
existingStudent.setName(student.getName());
existingStudent.setAge(student.getAge());
existingStudent.setCity(student.getCity());
return studentRepository.save(existingStudent);
}
}

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")
@RestController
public class StudentController {
@Autowired
private StudentService studentService;
@PostMapping
public Student addStudent(@RequestBody Student student){
return studentService.addStudent(student);
}
@GetMapping
public List<Student> getStudents(){
return studentService.getStudents();
}
@GetMapping("/{id}")
public Student getStudentById(@PathVariable int id){
return studentService.getStudentById(id);
}
@PutMapping
public Student updateStudent(@RequestBody Student student){
return studentService.updateStudent(student);
}
@DeleteMapping("/{id}")
public String deleteStudent(@PathVariable int id){
return studentService.deleteStudent(id);
}
}

Check why I used @CrossOrigin(“*”): https://spring.io/guides/gs/rest-service-cors

Okay, Now Right-click on the DemoApplication.java 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 application.properties 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
Senura Vihan Jayadeva

Written by Senura Vihan Jayadeva

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

No responses yet