What is @RequestBody and how is it used?

When building REST APIs, we often need to accept data in the request body, especially for operations like creating or updating resources. Without @RequestBody, we wouldn't be able to easily map the incoming request data to a Java object.

What is it?

@RequestBody is an annotation in Spring MVC used to bind the HTTP request body (typically in JSON or XML format) to a Java object. It helps in deserializing the incoming request data into a model object.

How is it used?

You use @RequestBody in a controller method to map the request data directly to the object parameter.

Example:

@PostMapping("/users")
public String createUser(@RequestBody User user) {
    userService.saveUser(user);
    return "User created";
}

In this example, when a POST request is made to /users with a JSON payload like:

{
  "name": "John",
  "email": "john@example.com"
}

Spring will automatically convert the JSON data into a User object.

Key point:

- Ensure the request content-type is set to application/json for proper mapping.

@RequestBody makes it easier to handle incoming JSON or XML data in Spring applications.