Use @RequestBody with optional body in latest Spring v4

Mike Powell picture Mike Powell · Feb 24, 2015 · Viewed 62.7k times · Source

How do I make body optional in REST API calls when using @RequestBody annotation in Spring?

With Spring's latest version, if you use @RequestBody annotation, it makes client to send body all the time without making it optional.

I tried @RequestBody (required=false) but that didn't work & still my request comes as null.

How do I manage to get request converted to proper required object without making body mandatory?

For eg:

@RequestMapping(value="/add/employee", method=RequestMethod.POST)
public void addEmployee(@RequestBody Employee employee){
    // ...
}

Here, I want to add employee using POST but without body. How do I do that? Spring latest version throws error "body missing" if I send empty body...

Answer

Jack Dorson picture Jack Dorson · Feb 24, 2015

@Santosh, I'm not sure which required argument you're referring. Mike already mentioned that he tried using @RequestBody (required=false) and request was still null. May be you can elaborate more & give example.

@Mike, probably you can try to have another separate converter that will serve your purpose.

Note: I noticed same issue with Spring v4.1.6 & Mike could be using that as he mentioned he is using latest version.