Send JSON objects via POST to Spring Boot Controllers

Creating and persisting business objects using Spring Boot is amazingly easy. Assume you create an API for simple CRUD methods and want to create an entity based on data entered by your frontend users. In the old times, you would probably populate several POST fields in a key-value style and create your business object manually from those fields.

Spring Boot offers an easier solution. As long as your internal data model equals the frontend’s data model, you can use the @Valid On @RequestBody Controller Method Arguments to automatically create the object from a JSON-serialized request and execute the necessary validation logic.

Preparing the Backend

First, we create an entity with some basic fields and validators:

package net.knasmueller.example.Entity;

import lombok.Data;

import javax.persistence.Entity;
import javax.persistence.Id;
import java.util.Date;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

@Entity

@Data
public class Person {
    @NotNull
    @Size(min = 1, max = 60)
    private String name;

    @Id
    private String email;

    @NotNull
    private Date birthDate;
}

The more interesting piece is the controller. Here, we define a create method accepting a single argument of the type of our entity (Person):

// ...

    @PostMapping
    public ResponseEntity create(@Valid @RequestBody Person person) {
        // make sure to check whether the new person does not already exist
        return ResponseEntity.ok(personService.save(person));
    }

With the @RequestBody annotation, Spring Boot automatically deserializes the JSON object in the POST request and creates a Person object from it. The @Valid annotation makes sure that all the defined validations are executed (for example, the string name must not exceed 60 characters).

Sending the Frontend Request

Our goal is to send a JSON encoded object with all the necessary parameters directly to the Spring Boot REST endpoint.

You may use a frontend framework such as Vue or Angular which have a great JSON support, but in this example we’ll simply use Postman:

Which Validations Can I Use?

There are a few validations provided by Spring Boot listed below – however, you can easily write your own and use them as annotations as explained here.

  • AssertFalse
  • AssertTrue
  • DecimalMax
  • DecimalMin
  • Digits
  • Email
  • Future
  • FutureOrPresent
  • Max
  • Min
  • Negative
  • NegativeOrZero
  • NotBlank
  • NotEmpty
  • NotNull
  • Null
  • Past
  • PastOrPresent
  • Pattern
  • Positive
  • PositiveOrZero
  • Size
Do NOT follow this link or you will be banned from the site!