Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 331
membersound Avatar asked Mar 03 '15 10:03

membersound


People also ask

How do you return a Boolean type?

The boolean returned represents the value true if the string argument is not null and is equal, ignoring case, to the string “true”, otherwise return false. boolean booleanValue() : This method returns the value of this Boolean object as a boolean primitive.

Can you return a boolean?

Java Boolean equals() methodThe equals() method of Java Boolean class returns a Boolean value. It returns true if the argument is not null and is a Boolean object that represents the same Boolean value as this object, else it returns false.

Why you shouldn't use booleans in rest APIS?

If not carefully considered, booleans can: Obstruct API Extensibility. Mask and obfuscate Domain Clarity. Hamper Code Readability and Maintainability.


1 Answers

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();
}
like image 122
ci_ Avatar answered Sep 20 '22 11:09

ci_