membersound
membersound

Reputation: 86747

How to return a boolean value with rest?

I want to provide a boolean REST service that only provides true/false boolean response.

But the following does not work. Why?

@RestController
@RequestMapping("/")
public class RestService {
    @RequestMapping(value = "/",
        method = RequestMethod.GET,
        produces = MediaType.APPLICATION_XML_VALUE)
    @ResponseBody
    public Boolean isValid() {
        return true;
    }
}

Result: HTTP 406: The resource identified by this request is only capable of generating responses with characteristics not acceptable according to the request "accept" headers.

Upvotes: 18

Views: 67946

Answers (1)

ci_
ci_

Reputation: 8774

You don't have to remove @ResponseBody, you could have just removed the MediaType:

@RequestMapping(value = "/", method = RequestMethod.GET)
@ResponseBody
public Boolean isValid() {
    return true;
}

in which case it would have defaulted to application/json, so this would work too:

@RequestMapping(value = "/", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public Boolean isValid() {
    return true;
}

if you specify MediaType.APPLICATION_XML_VALUE, your response really has to be serializable to XML, which true cannot be.

Also, if you just want a plain true in the response it isn't really XML is it?

If you specifically want text/plain, you could do it like this:

@RequestMapping(value = "/", method = RequestMethod.GET, produces = MediaType.TEXT_PLAIN_VALUE)
@ResponseBody
public String isValid() {
    return Boolean.TRUE.toString();
}

Upvotes: 19

Related Questions