Introduction
In this chapter, we will cover everything about the @GetMapping annotation in Spring Boot.
@GetMapping Annotation Overview
What is @GetMapping?
The @GetMapping annotation in Spring Boot is used to create a mapping between HTTP GET requests and handler methods in a controller. It is a specialized version of the @RequestMapping annotation that is specifically designed to handle GET requests.
How @GetMapping Works
When a client sends an HTTP GET request to a specified URL, the @GetMapping annotation maps this request to a specific handler method in the controller. The method then processes the request and returns a response.
Important Attributes of @GetMapping
value: Defines the URI path that this method will handle. It can also be specified aspath.params: Specifies the parameters of the request that need to be matched for the method to be invoked.headers: Specifies the headers of the request that need to be matched for the method to be invoked.produces: Specifies the type of media types that the method produces (e.g.,application/json).
Key Features of @GetMapping
- Simplified Mapping:
@GetMappingprovides a straightforward way to map HTTP GET requests to specific methods. This makes the code more readable and easier to understand compared to using the more generic@RequestMappingannotation. - Request Parameters:
@GetMappingcan work with@RequestParamand@PathVariableto extract parameters from the request URL, allowing for dynamic and flexible request handling. - Content Negotiation: It supports content negotiation, which allows the method to return different representations of the same resource (e.g., JSON, XML) based on the client’s request headers.
- Response Handling: The method annotated with
@GetMappingcan return various types of responses, such as strings, objects (automatically converted to JSON or XML), or even views for rendering HTML.
Setting Up the Project
Using Spring Initializr
- Open Spring Initializr:
- Navigate to Spring Initializr in your web browser.
- Configure Project Metadata:
- Group:
com.company - Artifact:
springboot-crud-api - Name:
springboot-crud-api - Description:
Spring Boot CRUD API with GET endpoints - Package name:
com.company.crudapi - Packaging:
Jar - Java Version:
17(or the latest version available) - Spring Boot Version: Select the latest version of Spring Boot
- Group:
- Select Dependencies:
- Add the following dependencies:
- Spring Web
- Add the following dependencies:
- Generate and Download:
- Click the “Generate” button to download the project as a ZIP file.
Importing the Project into IntelliJ IDEA
- Open IntelliJ IDEA:
- Launch IntelliJ IDEA from your installed applications.
- Import the Project:
- On the welcome screen, click “Open or Import”.
- Navigate to the directory where you downloaded the Spring Initializr ZIP file.
- Select the ZIP file and click “Open”.
- IntelliJ IDEA will unzip the file and import the project.
- Configure Maven (if needed):
- IntelliJ IDEA will automatically detect the Maven build file (
pom.xml) and import the project. - If prompted, confirm any necessary Maven configurations.
- IntelliJ IDEA will automatically detect the Maven build file (
Creating the Employee Entity
Step 1: Create the Employee Class
- Create a new package:
- In the
src/main/java/com/company/crudapidirectory, create a new package namedmodel.
- In the
- Create the Employee Class:
- Inside the
modelpackage, create a new class namedEmployee. - Add the following code to the
Employeeclass:
- Inside the
package com.company.crudapi.model;
public class Employee {
private Long id;
private String firstName;
private String lastName;
private String email;
// Constructors
public Employee() {}
public Employee(Long id, String firstName, String lastName, String email) {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
}
// Add Getters and Setters methods here
}
Explanation
- Fields: The
Employeeclass has four fields:id,firstName,lastName, andemail. - Constructors: The class includes a no-argument constructor and a parameterized constructor.
- Getters and Setters: The class provides getter and setter methods for each field, allowing other classes to access and modify the values.
Creating the REST Controller
Step 2: Create the EmployeeController Class
- Create a new package:
- In the
src/main/java/com/company/crudapidirectory, create a new package namedcontroller.
- In the
- Create the Controller Class:
- Inside the
controllerpackage, create a new class namedEmployeeController. - Add the following code to the
EmployeeControllerclass:
- Inside the
package com.company.crudapi.controller;
import com.company.crudapi.model.Employee;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.Arrays;
import java.util.List;
@RestController
public class EmployeeController {
private List<Employee> employees = Arrays.asList(
new Employee(1L, "Ramesh", "Fadatare", "ramesh.fadatare@example.com"),
new Employee(2L, "Suresh", "Kumar", "suresh.kumar@example.com"),
new Employee(3L, "Mahesh", "Yadav", "mahesh.yadav@example.com")
);
@GetMapping("/employees")
public List<Employee> getAllEmployees() {
return employees;
}
@GetMapping("/employees/{id}")
public Employee getEmployeeById(@PathVariable Long id) {
return employees.stream()
.filter(employee -> employee.getId().equals(id))
.findFirst()
.orElse(null);
}
@GetMapping("/employees/search")
public List<Employee> getEmployeesByLastName(@RequestParam String lastName) {
return employees.stream()
.filter(employee -> employee.getLastName().equalsIgnoreCase(lastName))
.collect(Collectors.toList());
}
}
1. GET All Employees
@GetMapping("/employees")
public List<Employee> getAllEmployees() {
return employees;
}
Explanation:
@GetMapping("/employees"): This annotation maps HTTP GET requests to the/employeesURL to thegetAllEmployeesmethod.- Method Logic: The method returns the full list of employees.
2. GET Employee by ID
@GetMapping("/employees/{id}")
public Employee getEmployeeById(@PathVariable Long id) {
return employees.stream()
.filter(employee -> employee.getId().equals(id))
.findFirst()
.orElse(null);
}
Explanation:
@GetMapping("/employees/{id}"): This annotation maps HTTP GET requests to the/employees/{id}URL to thegetEmployeeByIdmethod.@PathVariable Long id: This annotation binds the value of the{id}path variable to theidparameter in thegetEmployeeByIdmethod.- Method Logic: The method uses Java streams to filter the list of employees and find the one with the matching
id. If an employee with the givenidis found, it is returned; otherwise,nullis returned.
3. GET Employees by Last Name
@GetMapping("/employees/search")
public List<Employee> getEmployeesByLastName(@RequestParam String lastName) {
return employees.stream()
.filter(employee -> employee.getLastName().equalsIgnoreCase(lastName))
.collect(Collectors.toList());
}
Explanation:
@GetMapping("/employees/search"): This annotation maps HTTP GET requests to the/employees/searchURL to thegetEmployeesByLastNamemethod.@RequestParam String lastName: This annotation binds the value of thelastNamequery parameter to thelastNameparameter in thegetEmployeesByLastNamemethod.- Method Logic: The method uses Java streams to filter the list of employees and find those whose last name matches the provided value. The matching employees are returned as a list.
Running the Application
Step 3: Run Your Spring Boot Application
- Open Application Class:
- Ensure that the main application class (annotated with
@SpringBootApplication) is open.
- Ensure that the main application class (annotated with
- Run the Application:
- In IntelliJ IDEA, right-click the main application class and select “Run ‘SpringbootCrudApiApplication'”.
- Alternatively, open a terminal, navigate to the project directory, and run
mvn spring-boot:run.
Step 4: Test All the GET REST APIs
- GET All Employees:
- Request:
GET http://localhost:8080/employees - Response:

- Request:
- GET Employee by ID:
- Request:
GET http://localhost:8080/employees/1 - Response:

- Request:
- GET Employees by Last Name:
- Request:
GET http://localhost:8080/employees/search?lastName=Kumar - Response:

- Request:
Conclusion
In this chapter, we covered the @GetMapping annotation in Spring Boot, which is used to handle HTTP GET requests. We created endpoints to retrieve all employees, an employee by ID, and employees by last name using the @GetMapping annotation. In the next chapter, we will explore the @PostMapping annotation for handling HTTP POST requests.