How to Make a Request Body Property 'required' in Spring Boot - Code Snippet

·

1 min read

I was struggling with a codebase that came with an almost-typeless request parameter type, in Java Spring Boot. The controller header looks like this:

@RequestMapping("/my-end-point")
@ResponseBody
public Map<String, Object> doSomething(@RequestParam Map<String, Object> param) {}

It is very liberal about what could go inside the body, no type-checking, and it wouldn't care if the required property was present and/or absent.

I can use a DTO (data transfer object) though.

@Setter
@Getter
public class StateTransitionDto {
    @NotNull
    private Integer itemId;

    @NotNull
    private String nextStage;

    @NotNull
    private String nextStatus;
}

Then I could use it in a controller endpoint as follows:

@ResponseMapping("/my-end-point")
@ResponseBody
public ResponseEntity<StateTransitionDto> helloWorld(
  @Valid StateTransitionDto dto
) {
  return ResponseEntity.status(HttpStatus.OK).body(dto);
}

Here, @Valid comes from 'javax.validation.Valid'.

Now, if I leave a property in an http request for this end point, the server gives me a nice Bad Request Http 400 Error with detailed explanation of what went wrong. Below is an example of the error.

Screen Shot 2022-06-03 at 5.31.16 PM.png

Happy Coding!