Spring Boot GET REST API – @GetMapping Annotation

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 as path.
  • 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

  1. Simplified Mapping: @GetMapping provides 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 @RequestMapping annotation.
  2. Request Parameters: @GetMapping can work with @RequestParam and @PathVariable to extract parameters from the request URL, allowing for dynamic and flexible request handling.
  3. 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.
  4. Response Handling: The method annotated with @GetMapping can 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

  1. Open Spring Initializr:
  2. 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
  3. Select Dependencies:
    • Add the following dependencies:
      • Spring Web
  4. Generate and Download:
    • Click the “Generate” button to download the project as a ZIP file.

Importing the Project into IntelliJ IDEA

  1. Open IntelliJ IDEA:
    • Launch IntelliJ IDEA from your installed applications.
  2. 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.
  3. 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.

Creating the Employee Entity

Step 1: Create the Employee Class

  1. Create a new package:
    • In the src/main/java/com/company/crudapi directory, create a new package named model.
  2. Create the Employee Class:
    • Inside the model package, create a new class named Employee.
    • Add the following code to the Employee class:
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 Employee class has four fields: id, firstName, lastName, and email.
  • 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

  1. Create a new package:
    • In the src/main/java/com/company/crudapi directory, create a new package named controller.
  2. Create the Controller Class:
    • Inside the controller package, create a new class named EmployeeController.
    • Add the following code to the EmployeeController class:
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 /employees URL to the getAllEmployees method.
  • 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 the getEmployeeById method.
  • @PathVariable Long id: This annotation binds the value of the {id} path variable to the id parameter in the getEmployeeById method.
  • 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 given id is found, it is returned; otherwise, null is 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/search URL to the getEmployeesByLastName method.
  • @RequestParam String lastName: This annotation binds the value of the lastName query parameter to the lastName parameter in the getEmployeesByLastName method.
  • 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

  1. Open Application Class:
    • Ensure that the main application class (annotated with @SpringBootApplication) is open.
  2. 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:
  • GET Employee by ID:
    • Request: GET http://localhost:8080/employees/1
    • Response: GetMapping - GET Employee by ID
  • GET Employees by Last Name:
    • Request: GET http://localhost:8080/employees/search?lastName=Kumar
    • Response: GetMapping - Employees by Last Name

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.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top