Search code examples
spring-bootpostrequest

How to read POST body in spring boot


I am building my knowledge of spring boot.

So far I have created:

  • Get request that returns hardcoded data - WORKS
  • Get request that uses path pram ID to return data - WORKS

I now want to try use a post request that gets the ID from the body (this is for learning not best practice as I know this would be to use it in the path).

However, my code keep returning '0' rather than the ID...

What am I doing wrong?

Controller

    @RestController
    public class spannerController {
    
      @Autowired
      CdRequestService cdRequestService;
    
      @GetMapping("/getData")
      public Optional<Request> getData() {
        Optional<Request> request;
        request = requestService.getRequest(101);
    
        return request;
      }
    
    
      @GetMapping("/getData/{id}")
      public Optional<Request> getData(@PathVariable("id") int id) {
        Optional<Request> request;
        request = requestService.getRequest(id);
    
        return request;
      }
    
      @PostMapping(value = "/getData",
          consumes = MediaType.APPLICATION_JSON_VALUE,
          produces = MediaType.APPLICATION_JSON_VALUE)
      public void getDataPost(@RequestBody PostRequest request) {
        System.out.println(request);
        System.out.println(request.getId());
      }
    }

Request Class

    public class PostRequest {
    
       int id;
    
      public PostRequest() {
      }
      public PostRequest(int id) {
        this.id = id;
      }
    
      public int getId() {
        return id;
      }
    
      public void setId(Integer id) {
        this.id = id;
      }
    
    }

Solution

  • Make sure that you are using org.springframework.web.bind.annotation.RequestBody and not io.swagger.v3.oas.annotations.parameters.RequestBody. That is a frequent problem. Everything else seems to be OK.