@PostMapping and @RequestBody Example in Spring MVC

In this Spring MVC tutorial, you are going to learn how to use the @PostMapping annotation to make your RESTful Web Service Endpoint be able to handle HTTP Post quest and read its JSON or XML body payload.

Sending JSON in HTTP Post Request

Let’s say we need to send the following JSON in our HTTP Post request to our RESTful Web Service Endpoint. The below JSON will be sent to the following URL for the purpose of creating a new user profile.

URL:

http://localhost:8080/api/users

JSON:

{
  "firstName":"Sergey",
  "lastName":"Kargopolov",
  "email":"[email protected]",
  "password":"123"
}

CURL to Send HTTP Post Request

And here is a CURL command to send the above JSON to the above-mentioned URL using HTTP Post.

curl -X POST \
  http://localhost:8080/api/users \
  -H 'cache-control: no-cache' \
  -H 'content-type: application/json' \
  -d '{
  "firstName":"Sergey",
  "lastName":"Kargopolov",
  "email":"[email protected]",
  "password":"123"
}'

So how do we accept this HTTP Post request and read it’s JSON content in the RESTful Spring MVC Web Services App?

@PostMapping to handle HTTP POST Requests

To be able to handle HTTP Post request sent by the above-mentioned CURL command we will need to create a @RestController class with a method annotated with @PostMapping. Like the one below:

@RestController
@RequestMapping("users")
public class UserController {

    @Autowired
    UserService userService;
 
    @PostMapping
    public UserRest createUser(@RequestBody UserDetailsRequestModel requestUserDetails) {
        UserRest returnValue = new UserRest();
                
        UserDto userDto = new UserDto();
        BeanUtils.copyProperties(requestUserDetails, userDto);

        UserDto createdUser = userService.createUser(userDto);
        BeanUtils.copyProperties(createdUser, returnValue);

        return returnValue;
    }
}

Notice that the method responsible for handling HTTP POST requests needs to be annotated with @PostMapping annotation.

To be able to convert the JSON sent as HTTP Body content into a Java object which we can use in our application we need to use the @RequestBody annotation for the method argument. Notice how the @RequestBody annotation is used to mark the method argument object into which the JSON document will be converted by Spring Framework.

createUser(@RequestBody UserDetailsRequestModel requestUserDetails)

Now the only missing detail here is that we do not have the UserDetailsRequestModel Java class into which the incoming JSON will be mapped by Spring Framework. Spring will create an instance of UserDetailsRequestModel Java class for us and will set object properties with the values specified in the JSON.

Convert JSON into our own custom class

When we use the @RequestBody to annotate the method argument we are telling the framework to convert the JSON or XML payload which is in the request body of HTTP request into the object of a given type. Let’s create a Java class into which the JSON or XML content will be converted.

UserDetailsRequestModel Java class

When creating this Java class it is important that the class property names match the names in the JSON document. So if we have this JSON document:

JSON:

{
  "firstName":"Sergey",
  "lastName":"Kargopolov",
  "email":"[email protected]",
  "password":"123"
}

Then we will create the class with the following fields. The name of the class is not important. What’s important is that the class field names match the key names in the JSON document.

public class UserDetailsRequestModel {
    private String firstName;
    private String lastName;
    private String email;
    private String password;
    
 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;
 }
 public String getPassword() {
  return password;
 }
 public void setPassword(String password) {
  this.password = password;
 }
    
}

Accepting JSON or XML

To make your method annotated with @PostMapping be able to accept @RequestBody in JSON and XML using the following annotation:

@PostMapping(
        consumes = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE}
)

Here is how our method with this annotation will look like:

 
@PostMapping(
        consumes = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE}
)
public UserRest createUser(@RequestBody UserDetailsRequestModel requestUserDetails) {
    UserRest returnValue = new UserRest();
            
    UserDto userDto = new UserDto();
    BeanUtils.copyProperties(requestUserDetails, userDto);

    UserDto createdUser = userService.createUser(userDto);
    BeanUtils.copyProperties(createdUser, returnValue);

    return returnValue;
}

Responding with JSON or XML

If you want your Web Service Endpoint to be able to respond with JSON or XML, then update your @PostMapping annotation to this one:

@PostMapping(
        consumes = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE}
        produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE}
)

and to make your Web Service Endpoint respond with XML, provide the below Accept HTTP Header in the Request:

accept: application/xml

here is an example of CURL command with this Accept HTTP Header.

curl -X POST \
  http://localhost:8080/api/users \
  -H 'accept: application/xml' \
  -H 'cache-control: no-cache' \
  -H 'content-type: application/json' \
  -d '{
  "firstName":"Sergey",
  "lastName":"Kargopolov",
  "email":"[email protected]",
  "password":"123"
}'

Notice that in the above curl command the content type of Request Body is application/json but the content type of the Response body will be used based on the value set in the Accept Header.

And this is it! I hope this Spring MVC tutorial is of some value to you.

If you are interested to learn more about Spring MVC, please check the below list of video courses which might take your skills to a whole new level.