Andrew Kim
Andrew Kim's Blog

Andrew Kim's Blog

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

Andrew Kim's photo
Andrew Kim
·Jun 3, 2022·

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:

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.

public class StateTransitionDto {
    private Integer itemId;

    private String nextStage;

    private String nextStatus;

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

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!

Share this