In the previous blog, we have learned to generate spring boot code from our swagger using swagger codegen.
Today we will see how to create Rest APIs in java using the spring boot framework, we have already designed our employee management service swagger now let's write the implementation code for each endpoint and graphQL is the latest web service where there is one endpoint that provides all operations and response.
Before we start, you need to have a basic understanding of Rest API and HTTP.
Requirements
- IDE ( we are using eclipse with STS plugin)
- JDK 1.8
- Maven
What is Rest API and where is it used?
A Rest API is an architectural style for an API that uses HTTP methods to update or access data, it's also called RESTful API or RESTful web service.
Rest API is used as a web service by which clients interact and get data from a server in a stateless manner.
What are HTTP methods and their operation?
HTTP defines a set of methods (also referred to as a verb) to indicate the operation or action to be performed for a given resource or endpoint in the server example bank user may request for his bank statement, social media fetching all news posts from the server.
we will write the code for the below endpoints in our spring boot REST API.
HTTP method
|
Operation performed
|
URL
|
Operation description
|
POST |
Create |
/employee |
Add an employee |
GET |
Read |
/employee |
Fetch all employee details |
GET |
Read |
/employee/{employeeId}} |
Fetch specific employee details based on Id |
PUT |
Update/Replace |
/employee/{employeeId} |
Update specific employee details based on Id |
DELETE |
Delete |
/employee/{employeeid} |
Delete specific employee details based on Id
|
Maven dependencies
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.5.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
Spring boot Annotation for Rest API
- In spring, the class which contains methods to handle incoming HTTP requests are called the controller class it must be annotated with @Controller or @RestController can use any one of them.
- @RequestMapping annotation is used to define endpoint or resources which take URL values and are written inside a controller class. It can be applied at class and method levels. If the incoming request URL matches with URL defined in @RequestMapping then the method is executed. e.g.
- @RequestHeader is used to specify the HTTP header value for the endpoint we need to define the parameter name in it. e.g. @RequestHeader(value="x-requestid")
- @PathVariable is used to species the path values that will be present in the URL, we need to define the parameter name in it e.g. @PathVariable("employeeid")
- @RequestBody is used to define the HTTP request body it can be a POJO class. e.g. @RequestBody Employee employeeDetails.
package com.employee.example.api;
import com.employee.example.model.Employee;
import com.employee.example.model.Employees;
import com.employee.example.service.EmployeeManagamentService;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Optional;
@javax.annotation.Generated(value = "io.swagger.codegen.languages.SpringCodegen", date = "2021-09-12T10:02:10.313+05:30")
@Controller
public class EmployeeApiController implements EmployeeApi {
@Autowired
private EmployeeManagamentService employeeManagamentService;
@Override
public ResponseEntity<Employees> getEmployee(
@RequestHeader(value = "x-requestid", required = true) String xRequestid) {
Employees employees = employeeManagamentService.getEmployees();
return ResponseEntity.ok().body(employees);
}
@Override
public ResponseEntity<Employee> getEmployeeBasedOnId(
@RequestHeader(value = "x-requestid", required = true) String xRequestid,
@PathVariable("employeeid") String employeeid) {
Employee employee = employeeManagamentService.getEmployeeDetailsById(Integer.parseInt(employeeid));
return ResponseEntity.ok().body(employee);
}
@Override
public ResponseEntity<Void> addEmployee(@RequestHeader(value = "x-requestid", required = true) String xRequestid,
@Valid @RequestBody Employee employeeDetails) {
employeeManagamentService.createEmployee(employeeDetails);
return ResponseEntity.noContent().build();
}
@Override
public ResponseEntity<Void> deleteEmployeeBasedOnId(
@RequestHeader(value = "x-requestid", required = true) String xRequestid,
@PathVariable("employeeid") String employeeid) {
employeeManagamentService.deleteEmployeeDetailsById(employeeid);
return ResponseEntity.noContent().build();
}
@Override
public ResponseEntity<Void> updateEmployeeBasedOnId(
@RequestHeader(value = "x-requestid", required = true) String xRequestid,
@Valid @RequestBody Employee employeeDetails) {
employeeManagamentService.updateEmployeeDetailsById(employeeDetails.getId(), employeeDetails);
return ResponseEntity.noContent().build();
}
}
Creating Service class
package com.employee.example.service;
import java.util.List;
import org.springframework.stereotype.Service;
import com.employee.example.model.Employee;
import com.employee.example.model.Employees;
import com.employee.example.repo.EmployeeRepo;
@Service
public class EmployeeManagamentService {
private EmployeeRepo employeeRepo = new EmployeeRepo();
public Employee getEmployeeDetailsById(int employeeId) {
return employeeRepo.getEmployee(employeeId);
}
public Employees getEmployees() {
Employees employees = (Employees) employeeRepo.getEmployees();
return employees;
}
public void updateEmployeeDetailsById(int employeeId, Employee updatedEmployee) {
employeeRepo.updateEmployeeDetailsById(employeeId, updatedEmployee);
}
public void createEmployee(Employee employee) {
employeeRepo.createEmployee(employee);
}
public void deleteEmployeeDetailsById(String employeeId) {
employeeRepo.deleteEmployeeDetailsById(Integer.parseInt(employeeId));
}
}
package com.employee.example.repo;
import java.util.List;
import com.employee.example.model.Employee;
import com.employee.example.model.Employees;
public class EmployeeRepo {
private List<Employee> employees = new Employees();
public Employee getEmployee(int employeeId) {
return getEmployeeBasedonId(employeeId);
}
public List<Employee> getEmployees() {
return employees;
}
public void updateEmployeeDetailsById(int employeeId, Employee updatedemployee) {
Employee employee = getEmployeeBasedonId(employeeId);
employees.set(employees.indexOf(employee), updatedemployee);
}
public void createEmployee(Employee employee) {
employees.add(employee);
}
public void deleteEmployeeDetailsById(int employeeId) {
Employee employee = getEmployeeBasedonId(employeeId);
employees.remove(employee);
}
private Employee getEmployeeBasedonId(int id) {
return employees.stream().filter(employee -> employee.getId() == id).findFirst().get();
}
}
SpringBoot Application
- It enables auto-configuration features of spring boot.
- It does component scanning (scan all package) and create beans(objects) that can be used in our application. Beans will be created from our controller and service class during component scanning.
- Configure the embedded tomcat for us to test our REST API (endpoints).
package com.employee.example;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.ExitCodeGenerator;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@SpringBootApplication
@EnableSwagger2
@EnableAutoConfiguration
public class Swagger2SpringBoot {
public static void main(String[] arguments) throws Exception {
new SpringApplication(Swagger2SpringBoot.class).run(arguments);
}
}