开发者

How to represent boolean-type fields in Web API results

I am designing a REST Web API, and I am unsure of how to model certain parts of the response.

I think an example of the output will be most illustrative, so here it is.

This:

<packages>
  <package>
    <name>My Package, Yay!</name>
    <description>This is my package, Yay!</description>
    <features>
      <text_overlays />
      <localizable />
      <!-- Only features that are true for this package are listed -->
    </features>
  </packag开发者_如何学JAVAe>
</packages>

Or this:

<packages>
  <package>
    <name>My Package, Yay!</name>
    <description>This is my package, Yay!</description>
    <features>
      <text_overlays>True</text_overlays>
      <localizable>True</localizable>
      <audio>False</audio>
      <another_feature>False</another_feature>
      <this_aint_your_fathers_feature>False</this_aint_your_fathers_feature>
      <every_other_feature_that_exists_listed_here_too>False</every_other_feature_that_exists_listed_here_too>
    </features>
  </package>
</packages>

Basically, I have boolean fields, and it seems overly verbose to specify them all if many are false.

I am thinking about using the presence of an element as indicating whether it is true or false, but in the same thought I worry this would be a bad practice. It certainly seems less discoverable, but I'm not sure there's much value in discoverability here.

Is there a consensus on this sort of issue?

From a consuming client's perspective, I don't see too much difference. Testing for the presence of the element shouldn't be any more complicated than checking the value of the element.

Also, I expect there may be up to a dozen or possibly two dozen of these type of parameters, so it's not like there would be hundreds or thousands of them.

Lastly, we intend for our API to be used with XML and JSON. The JSON equivalent would be omitting the properties, and again from a consuming client perspective I see little difference between the two.

We have the opportunity to do this correctly from the beginning, and that is our goal.

What advice is there?


If the decision comes down to being explicit or implicit, I'd default to explicit to remove any possible confusion. The entity being represented has those attributes regardless of whether you send them or not, but you should include a complete representation.


Definitely the second method. This allows for more flexibility and when the parser is looping, checking wether a value is not true, it can stop when it finds the value instead of having to parse the whole file.

Besides, the boolean data type is supported by JSON.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜