Spring Boot PUT REST API – @PutMapping Annotation

Introduction

In this chapter, we will cover the @PutMapping annotation in Spring Boot. The @PutMapping annotation is used to handle HTTP PUT requests, which are typically used to update existing resources. We will create endpoints to update resources using this annotation, focusing on the Employee entity as our primary example.

Understanding @PutMapping Annotation

What is @PutMapping?

The @PutMapping annotation in Spring Boot is used to map HTTP PUT requests to specific handler methods in a controller. It is a specialized version of the @RequestMapping annotation designed specifically for handling PUT requests, which are usually used for updating existing resources.

How @PutMapping Works

When a client sends an HTTP PUT request to a specified URL, the @PutMapping annotation maps this request to a specific handler method in the controller. The method processes the request, typically updating a resource on the server, and returns a response.

Key Features of @PutMapping

  1. Simplified Mapping: @PutMapping provides a clear and concise way to map HTTP PUT requests to specific methods, making the code more readable and maintainable.
  2. Handling Update Operations: It is specifically designed for update operations, making it easier to handle requests that modify existing resources.
  3. Integration with @RequestBody: Often used in conjunction with @RequestBody to bind the request body to a method parameter, allowing for easy processing of complex data structures during an update.
  4. Path Variables and Query Parameters: Supports the use of @PathVariable and @RequestParam annotations to extract values from the URL and query parameters, making the method flexible and dynamic.

Example Use Case

A common use case for @PutMapping is updating a resource, such as updating an employee’s details in a database. The client sends the updated data in the request body, and the server processes the request and updates the resource accordingly.

Setting Up the Project

We will continue using the project named springboot-crud-api that we created in the previous chapters.

Creating the Employee Entity

We already have the Employee entity created in the previous chapters. For reference, here is 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;
    }

    // Getters and Setters
    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
}

Creating the REST Controller

Step 1: Update the EmployeeController Class

  1. Create or Update the Controller Class:
    • In the src/main/java/com/company/crudapi/controller directory, open or create the EmployeeController class.
    • Add the following code to the EmployeeController class:
@PutMapping("/employees/{id}")
public Employee updateEmployee(@PathVariable Long id, @RequestBody Employee updatedEmployee) {
    return employees.stream()
            .filter(employee -> employee.getId().equals(id))
            .findFirst()
            .map(employee -> {
                employee.setFirstName(updatedEmployee.getFirstName());
                employee.setLastName(updatedEmployee.getLastName());
                employee.setEmail(updatedEmployee.getEmail());
                return employee;
            })
            .orElse(null);
}

Explanation:

  • @PutMapping("/employees/{id}"): This annotation maps HTTP PUT requests to the /employees/{id} URL to the updateEmployee method.
  • @PathVariable Long id: This annotation binds the value of the {id} path variable to the id parameter in the updateEmployee method.
  • @RequestBody Employee updatedEmployee: This annotation binds the request body to the updatedEmployee parameter in the updateEmployee method.
  • Method Logic: The method uses Java streams to find the employee with the matching id. If an employee with the given id is found, its details are updated with the data from the updatedEmployee object. The updated employee is then returned. If no employee is found, null is returned.

Complete Code – EmployeeController

package com.company.crudapi.controller;

import com.company.crudapi.model.Employee;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@RestController
public class EmployeeController {

    private List<Employee> employees = new ArrayList<>(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());
    }

    @PostMapping("/employees")
    public Employee createEmployee(@RequestBody Employee employee) {
        employee.setId((long) (employees.size() + 1));
        employees.add(employee);
        return employee;
    }

    @PutMapping("/employees/{id}")
    public Employee updateEmployee(@PathVariable Long id, @RequestBody Employee updatedEmployee) {
        return employees.stream()
                .filter(employee -> employee.getId().equals(id))
                .findFirst()
                .map(employee -> {
                    employee.setFirstName(updatedEmployee.getFirstName());
                    employee.setLastName(updatedEmployee.getLastName());
                    employee.setEmail(updatedEmployee.getEmail());
                    return employee;
                })
                .orElse(null);
    }
}

Running the Application

Step 2: 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 3: Test the PUT REST API

  • PUT Update Employee:
    • Request: PUT http://localhost:8080/employees/1
    • Request Body:
{
    "firstName": "Ram",
    "lastName": "Fadatare",
    "email": "ram.fadatare@example.com"
}
  • Response: Spring Boot PUT REST API – @PutMapping Annotation

Conclusion

In this chapter, we covered the @PutMapping annotation in Spring Boot, which is used to handle HTTP PUT requests. We created an endpoint to update an employee using this annotation and explained important attributes of both @PutMapping and @RequestBody annotations. In the next chapter, we will explore the @DeleteMapping annotation for handling HTTP DELETE requests.

Leave a Comment

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

Scroll to Top