How to Create a Simple Spring Boot API? - 3

 In this blog, we will learn how to create a simple REST API. We are going to create two REST APIs. First API will provide us information on a single employee. The second API will give us the information of a list of employees. We will learn how to create a simple spring boot API step by step.

Step 1: We will create a bean class. Here we will keep the employee's information. Therefore we took the three variables in the bean (Employee) class. And created a getter/setter method for each variable. Also created a constructor with arguments.
public int id;
public String name;
public String mail;

public Employee(int id, String name, String mail) {
this.id = id;
this.name = name;
this.mail = mail;
}
Spring boot bean class

Step 2: We will create two spring boot rest APIs in our controller class. We will call both Rest APIs from the browser.
Required Annotation -
  1. @RestController - Consist of both @Controller and @ResponseBody annotation. So act as a Controller and respond as API. Class level annotation.
  2. @GetMapping    - Use to get data from the server. Method level annotation. Inside the @GetMapping("/employee") is the endpoint. We have to use that with a URL to access a particular API.

Spring Boot Controller Class

Here we created two simple functions. And we added @GetMapping annotation, so both functions has been API.

First API - @GetMapping("/employee") 
// Single Employee  (http://localhost:8080/Employee)
@GetMapping("/employee")
public Employee employee(){
Employee employee = new Employee(1,"Roman","roman@gmail.com");
return employee;
}
Here we just assigned the values for a single employee in the Employee class and returned it as an API response.

Second API - @GetMapping("/employees") 
// All Employee   (http://localhost:8080/Employees)
@GetMapping("/employees")
public List<Employee> employees(){
List<Employee> employees = new ArrayList<>();
employees.add(new Employee(1,"Roman","roman@gamil.com"));
employees.add(new Employee(2,"sarker","sarker@gmail.com"));
employees.add(new Employee(3,"Hasib", "hasib@gmail.com"));
return employees;
}
Here we assigned a list of employee information in the Employee class using the constructor. And returned API all employee information. Remember, here return type is List of Employee class.

Source Code : https://github.com/Roman-Sarker/RomanTechLife_SrpingBoot.git

All ways to get parameters from client to API

Post a Comment

0 Comments