Programming · free software · the open webSubscribe via RSS

Why Should API Fields Include Units?

From the earlier reference collection. Read the current software blog.

A numeric value has little meaning until clients know its unit, scale, and measurement context.

Numbers do not explain themselves

An API response such as {"temperature": 18} leaves a client guessing. Is that 18 degrees Celsius, Fahrenheit, or a sensor-specific integer scale? The JSON number is syntactically valid, but its meaning is incomplete. A dashboard might label it incorrectly, while an alert could compare it with a threshold expressed in another unit.

Units matter for every physical quantity, including distance, speed, pressure, rainfall, and energy. They can matter for counts and rates too: a value of 4 might mean events per minute, events per hour, or a total for a reporting period.

Put the unit where clients can find it

Document units in a field description that is part of the API’s schema or reference. For example, describe temperature_c as air temperature in degrees Celsius. A suffix in the field name can be especially helpful when clients encounter a payload without its surrounding documentation.

For a larger measurement object, an explicit unit field can work well: {"value": 18, "unit": "Cel"}. This pattern is useful when the unit can vary by record. If every value in an endpoint shares the same unit, repeating it in each row may add clutter; a fixed, prominent schema description can be clearer.

Explain the measurement as well as the unit

A unit label does not answer every interpretation question. Document whether a distance is measured along a route or as a straight line, whether a temperature is instantaneous or averaged, and what interval a rate covers. Use a consistent convention for spelling and capitalization so clients do not have to infer whether C, celsius, and degC mean the same thing.

For example, a public reading might be described as water temperature in degrees Celsius, observed at the stated time. That tells a client both how to display the number and what event the timestamp refers to.

Check the contract with an example

Include a sample response alongside field definitions. Ask whether someone can use it to convert, compare, or label each quantity without contacting the provider. If a value is an identifier rather than a measurement, say so instead of attaching a misleading unit.

Before changing an established unit, treat the change as a compatibility decision. Document the new meaning and version the interface or add a distinct field where needed. Clear units turn numbers from opaque tokens into values that users can safely combine and explain.

Suggest a correction · All posts