1

Let's say I have a REST API that needs to return the width of an object, but that width may either be a specific value or a range of values. What would be the best practice for designing the API to handle this?

For example:

"width": 35.5
"width": {
  "minimum": 34.2,
  "maximum": 36.8
}

Would it be best to simply specify the same value as minimum and maximum?

"width": {
  "minimum": 35.5,
  "maximum": 35.5
}

Or use a different label (such as "width_range") for a range and only return one or the other?

2
  • Would this depend on the "type" of the object? Aug 2, 2022 at 17:55
  • @StefanRendevski No, unfortunately; there is a mix of "types," but the odd object that has a range instead of a specific value may belong to any of them.
    – jem473
    Aug 2, 2022 at 18:00

1 Answer 1

1

This may very well depend on how your API is to be used, and how the "width" property of these objects is consumed, so without knowing specifics, I can only give a general recommendation.

I would suggest that you make the possible difference in the type of width explicit, by exposing a custom Width type, for example, with the following structure:

"width": {
  "type": "exact",
  "value": 35.5
}

"width": {
  "type": "range",
  "value": {
    "minimum": 34.2,
    "maximum": 36.8
  }
}

This would allow clients of your API to then also create an explicit Width type, and a corresponding class hierarchy, and work with that abstraction with specific implementations, in case client code has to work with these values in some way.

This could technically be accomplished by inspecting the type of "width" as per the example in your question, but from my perspective, it is easier to rely on an explicit enumeration, rather than the data type of the property itself.

1
  • For my use case client code will almost definitely need to work with the ranges, so this explicitness is an excellent solution. Thanks.
    – jem473
    Aug 2, 2022 at 18:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.