@PostMapping and @RequestBody Example in Spring Boot REST

In this Spring Boot REST tutorial, you will learn how to use the @PostMapping annotation to make your RESTful Web Service Endpoint able to handle HTTP Post requests and read its JSON or XML body payload.

If you are also interested in using @GetMapping, @PutMapping and @DeleteMapping annotations, check the following tutorial “@PostMapping, @GetMapping, @PutMapping, @DeleteMapping“.

Sending JSON in HTTP Post Request

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

http://localhost:8080/api/users

JSON:

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

CURL to Send HTTP Post Request

Below is a CURL command to send the above JSON to the URL mentioned above 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 its JSON content Spring Boot REST application?

@PostMapping to handle HTTP POST Requests

To be able to handle HTTP Post requests sent by the above-mentioned CURL command, we will need to create a @RestController class. Our @RestController class will need to have 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 for handling HTTP POST requests needs to be annotated with @PostMapping annotation.

To convert the received JSON into a Java object, we can use the @RequestBody annotation. Notice how the @RequestBody annotation marks the method argument object into which the JSON document will be converted by Spring Framework.

createUser(@RequestBody UserDetailsRequestModel requestUserDetails)

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 the object’s properties with the values specified in the JSON.

Convert JSON into Object of Our class

When we use the @RequestBody to annotate the method argument, we tell the framework to convert the JSON or XML payload in the HTTP request body 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, the class property names must 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 what 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

Below is an example of a CURL command with the 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 the 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.

Read HTTP Request Body – Video Tutorial

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

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


1 Comment on "@PostMapping and @RequestBody Example in Spring Boot REST"


  1. can you please give an example for how to process multiple json array for postmapping using @requestbody in spring boot rest

    Reply

Leave a Reply

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