user1032531
user1032531

Reputation: 26311

How should REST API accept boolean values?

Resource 123 has a current configuration state and a default configuration state, and both of these configuration states can be represented by JSON.

A GET request to http://example.com/123/config will return the current configuration state, and a GET request to http://example.com/123/config?reset=true will return the default configuration state.

How should an API interpret boolean values? For instance:

Upvotes: 18

Views: 49881

Answers (2)

cassiomolin
cassiomolin

Reputation: 130997

True and false

The true and false literals are just fine to represent boolean values. They are quite descriptive and, if your API supports JSON, true and false are definitively the obvious choices.

Enumerations

In a few situations, however, you may want to avoid boolean values because they cannot be expanded. You may want to consider enumerations instead.

It may be a poor comparison but it might help you to get the main idea of this approach: have a look at CSS properties such as overflow or visibility. They allow expandable values instead of only true or false. So new values can be easily added without changing the property names.

So, for the situation described in your question, to retrieve the default state of a resource, I would support a query parameter such as status, that could have values such as default and current.

The following would return the default state of the resource:

GET /config?status=default HTTP/1.1
Host: example.com
Accept: application/json

And the following would return the current state of the resource:

GET /config?status=current HTTP/1.1
Host: example.com
Accept: application/json

If no query parameter is provided, you could that the client wants the current state of the resource.


If you need to restore the resource state to its default state, consider using PUT, sending the new representation of the resource in the request payload. Something like:

PUT /config/status HTTP/1.1
Host: example.com
Content-Type: application/json

{ 
  "value": "default" 
}

Upvotes: 14

rorschach
rorschach

Reputation: 2947

Whichever way you want it to, it's completely up to you as the architect/designer. true/false is the most syntactically correct version, make sure that one works and add the other options as sugar if you want.

Upvotes: 11

Related Questions