Spring Boot POST REST API – @PostMapping and @RequestBody

Introduction

In this chapter, we will cover the @PostMapping and @RequestBody annotations in Spring Boot. The @PostMapping annotation is used to handle HTTP POST requests, while the @RequestBody annotation is used to bind the request body to a method parameter. We will create endpoints to create resources using these annotations, focusing on the Employee entity as our primary example.

Understanding @PostMapping and @RequestBody Annotations

What is @PostMapping?

The @PostMapping annotation in Spring Boot is used to create a mapping between HTTP POST requests and handler methods in a controller. It is a specialized version of the @RequestMapping annotation designed specifically for handling POST requests.

How @PostMapping Works

When a client sends an HTTP POST request to a specified URL, the @PostMapping annotation maps this request to a specific handler method in the controller. The method processes the request and returns a response, often creating or updating a resource on the server.

Key Features of @PostMapping

  1. Simplified Mapping: @PostMapping provides a clear and concise way to map HTTP POST requests to specific methods, making the code more readable and maintainable.
  2. Handling Form Data and JSON: @PostMapping can handle various types of request bodies, including form data and JSON payloads, making it versatile for different use cases.
  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.

What is @RequestBody?

The @RequestBody annotation in Spring Boot is used to bind the body of an HTTP request to a method parameter in a controller. It allows Spring to automatically deserialize the JSON or XML data from the request body into a Java object.

How @RequestBody Works

When a client sends an HTTP request with a body (e.g., a JSON payload), the @RequestBody annotation extracts the body and binds it to a method parameter. This makes it easy to work with the data sent by the client.

Key Features of @RequestBody

  1. Automatic Deserialization: @RequestBody automatically deserializes the JSON or XML data from the request body into a corresponding Java object, simplifying data handling in the controller.
  2. Validation Support: It integrates with Spring’s validation framework, allowing you to validate the data before processing it, ensuring that only valid data is accepted.
  3. Ease of Use: By binding the request body directly to a method parameter, @RequestBody makes it easy to access and manipulate the data sent by the client.

Setting Up the Project

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

Creating the Employee Entity

We have already created the  Employee entity in the previous chapter. 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:
@PostMapping("/employees")
public Employee createEmployee(@RequestBody Employee employee) {
    employee.setId((long) (employees.size() + 1));
    employees.add(employee);
    return employee;
}

Explanation:

  • @PostMapping("/employees"): This annotation maps HTTP POST requests to the /employees URL to the createEmployee method.
  • @RequestBody Employee employee: This annotation binds the request body to the employee parameter in the createEmployee method.
  • Method Logic: The method assigns a new ID to the employee (based on the size of the employee list), adds the employee to the list, and returns the created employee.

Complete Code of EmployeeController Class

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;
    }
}

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:
    • Right-click the main application class in IntelliJ IDEA and select “Run ‘SpringbootCrudApiApplication'”.
    • Alternatively, open a terminal, navigate to the project directory, and run mvn spring-boot:run.

Step 3: Test the POST REST API

You cannot send a POST request using a standard web browser. Instead, you should use a REST client like Postman to send the POST request. Postman allows you to construct and send HTTP requests using various HTTP methods (GET, POST, PUT, DELETE, etc.), and it is especially useful for testing RESTful APIs.

Using Postman to Send a POST Request

  1. Open Postman: Launch the Postman application.
  2. Create a New Request: Click on the “New” button and select “Request”.
  3. Set the HTTP Method to POST: In the request builder, set the HTTP method to POST.
  4. Enter the URL: http://localhost:8080/employees
  5. Set the Request Body: Select the “Body” tab, choose “raw”, and set the format to JSON. Then, enter the JSON payload you want to send.
  6. Send the Request: Click the “Send” button to send the POST request
    • Request Body:
{
    "firstName": "Amit",
    "lastName": "Sharma",
    "email": "amit.sharma@example.com"
}
  • Response:

Spring Boot POST REST API - @PostMapping and @RequestBody

Conclusion

The @PostMapping and @RequestBody annotations in Spring Boot provide powerful and convenient ways to handle HTTP POST requests and bind request bodies to method parameters. @PostMapping simplifies the mapping of POST requests to handler methods, while @RequestBody enables automatic deserialization of JSON or XML data into Java objects. Together, they make it easy to process and validate data sent by clients, allowing for the creation of robust and maintainable web applications.  In the next chapter, we will explore the @PutMapping annotation for handling HTTP PUT requests.

Leave a Comment

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

Scroll to Top