Spring Boot is a popular framework for building RESTful web services in Java. In this blog post, we’ll explore how to process POST requests with JSON data in a Spring Boot RESTful API. We’ll look at the steps involved in reading JSON data from the request body and responding to the client with the data.



Prerequisites

  • Java 8 or later
  • Spring Boot 2.3.3 or later
  • An IDE such as IntelliJ or Eclipse
  • Gradle or Maven for building the project


Creating the Project

You can use the Spring Initializer website to create a new Spring Boot project. Select the following options:

  • Group: com.example
  • Artifact: post-json
  • Packaging: Jar
  • Java: 8
  • Spring Boot: 2.3.3
  • Dependencies: Web, Lombok

Download the project and import it into your IDE.



Writing the REST Controller

Next, we’ll write a REST controller to handle incoming POST requests with JSON data. Create a new class called PostJsonController and add the following code:

@RestController
public class PostJsonController {

  @PostMapping("/post-json")
  public ResponseEntity<String> postJson(@RequestBody Map<String, Object> data) {
    return ResponseEntity.ok("Received data: " + data);
  }

}

The @RestController annotation indicates that this class will handle REST requests. The @PostMapping annotation maps the incoming POST request to the postJson method. The @RequestBody annotation tells Spring Boot to read the request body as a Map of key-value pairs.



Testing the REST Controller

We can use curl to test the REST controller. Open a terminal window and run the following command:

curl -X POST -H "Content-Type: application/json" -d '{"name": "John Doe"}' http://localhost:8080/post-json

You should see the following response:

Received data: {name=John Doe}


Working with JSON Data in Spring Boot REST

In the previous section, we saw how to read JSON data from a POST request and return a response to the client. In this section, we’ll explore how to work with JSON data in the REST controller.



Parsing JSON Data

The Map that we used in the previous example is a generic data structure that can be used to hold any type of data. However, it may not always be the best data structure to use when working with JSON data.

We can use the ObjectMapper class from the com.fasterxml.jackson.databind package to parse JSON data into a Java object. Add the following code to the PostJsonController class:

@PostMapping("/post-json")
public ResponseEntity<String> postJson(@RequestBody User data) {
  return ResponseEntity.ok("Received data: " + data);
}

Create a new class called User and add the following code:

@Data
public class User {

  private String name;

}

The @Data annotation from the lombok library generates getters, setters, and a toString method for the User class.

Run the curl command again to test the REST controller:

curl -X POST -H "Content-Type: application/json" -d '{"name": "John Doe"}' http://localhost:8080/post-json

You should see the following response:

Received data: User(name=John Doe)


Validating JSON Data

We can use the @Valid annotation and the BindingResult class from the org.springframework.validation package to validate JSON data. Add the following code to the PostJsonController class:

@PostMapping("/post-json")
public ResponseEntity<String> postJson(@Valid @RequestBody User data, BindingResult result) {
  if (result.hasErrors()) {
    return ResponseEntity.badRequest().body("Invalid data: " + result.getAllErrors());
  }
  return ResponseEntity.ok("Received data: " + data);
}

Add the following code to the User class:

import javax.validation.constraints.NotBlank;

...

@NotBlank
private String name;

The @NotBlank annotation from the javax.validation.constraints package ensures that the name field is not blank.

Run the following curl command to test the REST controller with invalid data:

curl -X POST -H "Content-Type: application/json" -d '{"name": ""}' http://localhost:8080/post-json

You should see the following response:

Invalid data: [Field error in object 'user' on field 'name': rejected value []; code


Conclusion

In this blog post, we looked at how to process POST requests with JSON data in a Spring Boot RESTful API. We created a REST controller that maps the incoming POST request to a method that reads the request body as a Map of key-value pairs. We tested the REST controller using curl.



Leave a Reply