RequestBody
We define @RequestBody
to put in a request body.
The request body could be a class. **However, this class needs to have Getter and Setter for Spring to convert from JSON to POJO **
For example our controller:
@PostMapping(value = "/v{version}/meow", produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public Callable<ResponseEntity<MeowRequest>> greet(@PathVariable String version,
@RequestBody @Valid MeowRequest request) {
return () -> ResponseEntity.ok(request);
}
With our request body:
@Setter
@Getter
public class MeowRequest {
@NotNull
private Animal type;
}
With our Animal
public enum Animal {
DOG, CAT
}
Note: in here it will automatically convert into the correct enum for us. In the case that we provide a request body that doesn't have in the Enum
, it will throws error.
For example if we have a request
{
"type": "CAT1x"
}
It will throws exception:
JSON parse error: Cannot deserialize value of type `apis.dto.Animal` from String \"CAT1x\": not one of the values accepted for Enum class: [DOG, CAT]; nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type `apis.dto.Animal` from String \"CAT1x\": not one of the values accepted for Enum class: [DOG, CAT]\n at [Source: (PushbackInputStream); line: 2, column: 13] (through reference chain: apis.dto.MeowRequest[\"type\"])
For exception handling, we can refer to API Exception Handler