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
- Simplified Mapping:
@PostMapping
provides a clear and concise way to map HTTP POST requests to specific methods, making the code more readable and maintainable. - 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. - 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
- 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. - 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.
- 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
- Create or Update the Controller Class:
- In the
src/main/java/com/company/crudapi/controller
directory, open or create theEmployeeController
class. - Add the following code to the
EmployeeController
class:
- In the
@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 thecreateEmployee
method.@RequestBody Employee employee
: This annotation binds the request body to theemployee
parameter in thecreateEmployee
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
- 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:
- 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
- Open Postman: Launch the Postman application.
- Create a New Request: Click on the “New” button and select “Request”.
- Set the HTTP Method to POST: In the request builder, set the HTTP method to POST.
- Enter the URL:
http://localhost:8080/employees
- 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.
- Send the Request: Click the “Send” button to send the POST request
- Request Body:
{
"firstName": "Amit",
"lastName": "Sharma",
"email": "amit.sharma@example.com"
}
- Response:
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.