What is the proper way to design a REST API that takes a boolean argument?

Viewed 1105

Basically I have a rest API like this:

/api/drive

And it takes a body for PUT which is either "true" or "false".

I'm using dropwizard framework with Java, and boolean drive is one of my parameters in the PUT method of my resource class.

Everything works as expected, but I was testing on Postman and see even if I put another value like "notABoolean" in the request body, the request itself is still successful. It just treats it as "false". Does this align with REST principles, or does it make more sense to throw a 400 BAD REQUEST error if the body isn't true/false?

1 Answers

Does this align with REST principles, or does it make more sense to throw a 400 BAD REQUEST error if the body isn't true/false?

"It depends".

notABoolean

That's a perfectly reasonable text/plain document, but it isn't a valid application/json document.

As noted by Mike, Boolean.valueOf("notABoolean") has a well defined value; if you have described your API in a way that explicitly restricts this case, then you get what you get.

There are at least three possible status codes that might handle this case.

422 Unprocessable Entity is what you seem to have been expecting - it roughly translates to "yeah, the data is what you said it was, but that really doesn't make any sense here".

If you were to describe your API such that only application/json was reasonable, then this test would probably have produced either 415 Unsupported Media Type (because the client sent text/plain) or 400 Bad Request (because notABoolean is not a valid JSON value).

Of course, Strings are valid json values, so the payload below might land you in the same fix

"notABoolean"

It's an acceptable type, and it is valid, but you are back on the 422 train.

To get DropWizard to return the 422 for you "for free", look into the docs on validation.

Related